这道题用的是分治的思路。js实现可能会出现由于精度原因无法通过本地的单元测试,但是leetcode上面提交是能AC的。
Source Code
1 | var myPow = function (x, n) { |
Test Cases:
1 | test("test1", () => {//本地精度问题无法通过单元测试 |
前端小天才智多星班进修中
这道题用的是分治的思路。js实现可能会出现由于精度原因无法通过本地的单元测试,但是leetcode上面提交是能AC的。
1 | var myPow = function (x, n) { |
1 | test("test1", () => {//本地精度问题无法通过单元测试 |
时间复杂度:O(n)
1 | // Runtime: 168 ms, faster than 5.31% of JavaScript online submissions for Lowest Common Ancestor of a Binary Search Tree. |
1 | test("test1", ()=>{ |
时间复杂度:O(n)
1 | // Runtime: 84 ms, faster than 22.42% of JavaScript online submissions for Lowest Common Ancestor of a Binary Tree. |
1 | test("test1", ()=>{ |
时间复杂度:O(n)
1 | // Runtime: 64 ms, faster than 73.11% of JavaScript online submissions for Validate Binary Search Tree. |
时间复杂度:O(n)
1 | // Runtime: 68 ms, faster than 50.77% of JavaScript online submissions for Validate Binary Search Tree. |
1 | test("test1", ()=>{ |
原题:1. Two Sum
1 | // Runtime: 76 ms, faster than 52.22% of JavaScript online submissions for Two Sum. |
1 | test("test1", ()=>{ |
1 | //这个解法一直AC不过去,但是浏览器跑超时的test case速度还行。 |
和Three Sum类似,可以基于target + Three Some的方式写出类似的解答。
1 | var fourSum = function(nums, target) { |
思路:滑动窗口,维护一个size为k的大堆。滑动过程中把最老的元素poll,offer最新的元素后调整堆。
时间复杂度:O(n * logk)
由于窗口大小固定,我们并不需要去维持大堆,只要记录窗口内的最大值即可。这里采用 双关队列(Dequeue) 的思路。
时间复杂度:O(n)
1 | // Runtime: 192 ms, faster than 18.08% of JavaScript online submissions for Sliding Window Maximum. |
1 | test("test1", ()=>{ |
这道题主要考察优先队列(小堆)的用法,但是js里面没有优先队列,只能自己实现。具体可以参考leetcode上一个大神的实现:
priority-queue.js
1 | // Runtime: 196 ms, faster than 78.06% of JavaScript online submissions for Kth Largest Element in a Stream. |
1 | test("test1", ()=>{ |
原题:232. Implement Queue using Stacks
类似的题有:225. Implement Stack using Queues
栈是FILO,队列是FIFO,想用栈实现队列,用的是 “负负得正” 的思想。
1 | class Stack { |
1 | const queue = new MyQueue(); |
1 | // Runtime: 52 ms, faster than 83.97% of JavaScript online submissions for Valid Parentheses. |
1 | // Runtime: 76 ms, faster than 18.01% of JavaScript online submissions for Valid Parentheses. |
1 | test("test1", ()=>{ |
1 | /** |
1 | test("test1", ()=>{ |
1 | //brute force,很容易想到 |
1 | var detectCycle = function(head) { |
这个解法用的还是 Linked List Cycle里面的快慢双指针的思路。
外层循环通过快慢指针判断是否有环,内层循环找出环的起始点。
下面用一幅图解释下为什么内层循环这样做可以找到环的起始点:
假设链表起点到环起点距离为x1,环起点到快慢指针相遇节点距离为x3,环的长度为2*x2。
快慢指针相遇时慢指针走的距离是:
1 | slowDistance = x1 + x2 |
快指针有的距离是:
1 | fastDistance = x1 + x3 + 2 * x2 |
由于快指针移动速度是慢指针两倍:
1 | fastDistance = 2 * slowDistance |
由上可得:
1 | x1 = 2 * x2 - x3 |
x1
是链表起点到环起点的距离,2 * x2 - x3
是快指针绕回环起点的距离。因此只要以相同速度移动链表起点和快指针,它们第一次一定会在环起点相遇。
tag:
缺失模块。
1、请确保node版本大于6.2
2、在博客根目录(注意不是yilia根目录)执行以下命令:
npm i hexo-generator-json-content --save
3、在根目录_config.yml里添加配置:
jsonContent: meta: false pages: false posts: title: true date: true path: true text: false raw: false content: false slug: false updated: false comments: false link: false permalink: false excerpt: false categories: false tags: true