【104】二叉树的最大深度
两种解法,递归比较容易被想到,迭代还需要再思考?
1、递归
function maxDepth(root){ if(!root){ return 0; }else{ let left = maxDepth(root.left); let right = maxDepth(root.right); return Math.max(left,right)+1; }}
2、迭代,利用层序遍历累加
const maxDepth = root => { if (!root) return 0 let queue = [root], n = 0 console.log('queue',queue.length) while (queue.length) { let arr = [] while (queue.length) { let curr = queue.shift() console.log('curr',curr) console.log('arr',arr) if (curr.left) arr.push(curr.left) if (curr.right) arr.push(curr.right) } n++ queue = arr } return n}
【122】买卖股票的最佳时机2
两种解法:第一种是自己做出来的笨方法,第二种是参考了别人的思路
1、
/** * @param {number[]} prices * @return {number} */var maxProfit = function(prices) { if(prices.length < 2) return 0; let result = 0; let small = prices[0] for(var i = 0; i < prices.length; i++){ if(prices[i] < small || prices[i] == small){ small = prices[i]; }else{ if(prices[i] > prices[i+1]){ result += prices[i] - small; small = prices[i+1]; }else{ result += prices[i] - small; small = prices[i]; } } } return result;};
2、贪心算法,每天为一步,只取正收益, 负收益不要(设为0)。而每一天的收益 = 今天股价 - 昨天的股价。
var maxProfit = function(prices) { let sum = 0 for(let i=1; i<prices.length; i++) { sum += Math.max(prices[i] - prices[i-1], 0) } return sum};
【136】只出现一次的数字
方法有很多但要考虑时间复杂度,找出最优解,只要说不占用额外内存就要警惕
对异或运算符的应用
时间复杂度O(n),空间复杂度O(1)
只操作 nums 数组本身,不使用额外空间
n ^ n === 0 且 n ^ 0 === n
并且,异或遵循交换律
var singleNumber = function(nums) { let ans = 0; for(const num of nums) { ans ^= num; } return ans;};
【141】环形链表-一道引发深思的题目
吐槽:题目描述也抬不清晰了,搞了一个pos出来迷惑
奇葩解法一:不推荐
var hasCycle = function(head) { try{ JSON.stringify(head) }catch(e){ return true } return false };
哈希表判定法:借鉴大神的代码,但是看不懂?
var hasCycle = function(head) { const nodeCollection = new Map(); while(head) { if (nodeCollection.get(head)) return true; nodeCollection.set(head, 1) head = head.next; } return false;};
标准解法,必须掌握-》双指针解法
思路来源:先想象一下,两名运动员以不同速度在跑道上进行跑步会怎样?相遇!
通过使用具有不同速度的快、慢两个指针遍历链表,空间复杂度可以被降至O(1)。慢指针每次移动一步,而快指针每次移动两步
var hasCycle = function(head) { let first = head; let second = head; while(first && first.next) { first = first.next.next; second = second.next; if (first === second) return true; } return false;};
【155】最小栈
这题虽然tag是简单,但是对我来说还是有点难度的,如何用js去实现数据结构一致掌握的非常一般。后面要下功夫了。
利用辅助栈
var MinStack = function() { this.x_stack = []; this.min_stack = [Infinity];};MinStack.prototype.push = function(x) { this.x_stack.push(x); this.min_stack.push(Math.min(this.min_stack[this.min_stack.length - 1], x));};MinStack.prototype.pop = function() { this.x_stack.pop(); this.min_stack.pop();};MinStack.prototype.top = function() { return this.x_stack[this.x_stack.length - 1];};MinStack.prototype.getMin = function() { return this.min_stack[this.min_stack.length - 1];};
小结:审题。理解题意是很重要的,简单问题千万不要复杂化,多关注js实现数据结构的方式。