functionmaxSubArray(nums) { let max = nums[0], sum = 0; for (let num of nums) { sum = Math.max(num, sum + num); max = Math.max(max, sum); } return max; }
5. 移动零
给定一个数组 nums,将所有 0 移动到数组末尾,同时保持非零元素的相对顺序。
1 2 3 4 5 6 7 8 9
functionmoveZeroes(nums) { let j = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { [nums[i], nums[j]] = [nums[j], nums[i]]; j++; } } }
6. 有效的括号
判断字符串中的括号是否有效。
1 2 3 4 5 6 7 8 9 10 11
functionisValid(s) { const stack = []; const map = {')':'(', ']':'[', '}':'{'}; for (let c of s) { if (c === '(' || c === '[' || c === '{') stack.push(c); else { if (stack.pop() !== map[c]) returnfalse; } } return stack.length === 0; }
7. 删除排序数组中的重复项
原地删除有序数组中的重复元素。
1 2 3 4 5 6 7 8
functionremoveDuplicates(nums) { if (!nums.length) return0; let i = 0; for (let j = 1; j < nums.length; j++) { if (nums[j] !== nums[i]) nums[++i] = nums[j]; } return i + 1; }
8. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
1 2 3 4
functionmaxDepth(root) { if (!root) return0; return1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }
9. 爬楼梯
每次可以爬 1 或 2 阶楼梯,求有多少种方法爬到楼顶。
1 2 3 4 5 6 7
functionclimbStairs(n) { let a = 1, b = 1; for (let i = 2; i <= n; i++) { [a, b] = [b, a + b]; } return b; }
10. 合并区间
合并所有重叠的区间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionmerge(intervals) { if (!intervals.length) return []; intervals.sort((a, b) => a[0] - b[0]); const res = [intervals[0]]; for (let i = 1; i < intervals.length; i++) { let last = res[res.length - 1]; if (intervals[i][0] <= last[1]) { last[1] = Math.max(last[1], intervals[i][1]); } else { res.push(intervals[i]); } } return res; }