diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 96dc1ac3..a1e4f020 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -218,8 +218,33 @@ class Solution { ``` Python: - - +```Python +class Solution: + def threeSum(self, nums): + ans = [] + n = len(nums) + nums.sort() + for i in range(n): + left = i + 1 + right = n - 1 + if nums[i] > 0: + break + if i >= 1 and nums[i] == nums[i - 1]: + continue + while left < right: + total = nums[i] + nums[left] + nums[right] + if total > 0: + right -= 1 + elif total < 0: + left += 1 + else: + ans.append([nums[i], nums[left], nums[right]]) + while left != right and nums[left] == nums[left + 1]: left += 1 + while left != right and nums[right] == nums[right - 1]: right -= 1 + left += 1 + right -= 1 + return ans +``` Go: ```Go func threeSum(nums []int)[][]int{ @@ -256,6 +281,59 @@ func threeSum(nums []int)[][]int{ } ``` +javaScript: + +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ + +// 循环内不考虑去重 +var threeSum = function(nums) { + const len = nums.length; + if(len < 3) return []; + nums.sort((a, b) => a - b); + const resSet = new Set(); + for(let i = 0; i < len - 2; i++) { + if(nums[i] > 0) break; + let l = i + 1, r = len - 1; + while(l < r) { + const sum = nums[i] + nums[l] + nums[r]; + if(sum < 0) { l++; continue }; + if(sum > 0) { r--; continue }; + resSet.add(`${nums[i]},${nums[l]},${nums[r]}`); + l++; + r--; + } + } + return Array.from(resSet).map(i => i.split(",")); +}; + +// 去重优化 +var threeSum = function(nums) { + const len = nums.length; + if(len < 3) return []; + nums.sort((a, b) => a - b); + const res = []; + for(let i = 0; i < len - 2; i++) { + if(nums[i] > 0) break; + // a去重 + if(i > 0 && nums[i] === nums[i - 1]) continue; + let l = i + 1, r = len - 1; + while(l < r) { + const sum = nums[i] + nums[l] + nums[r]; + if(sum < 0) { l++; continue }; + if(sum > 0) { r--; continue }; + res.push([nums[i], nums[l], nums[r]]) + // b c 去重 + while(l < r && nums[l] === nums[++l]); + while(l < r && nums[r] === nums[--r]); + } + } + return res; +}; +``` diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index ff441bf7..ebbdc31a 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -165,11 +165,75 @@ class Solution { ``` Python: +```python +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + # use a dict to store value:showtimes + hashmap = dict() + for n in nums: + if n in hashmap: + hashmap[n] += 1 + else: + hashmap[n] = 1 + + # good thing about using python is you can use set to drop duplicates. + ans = set() + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + for k in range(j + 1, len(nums)): + val = target - (nums[i] + nums[j] + nums[k]) + if val in hashmap: + # make sure no duplicates. + count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val) + if hashmap[val] > count: + ans.add(tuple(sorted([nums[i], nums[j], nums[k], val]))) + else: + continue + return ans + +``` Go: +javaScript: +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function(nums, target) { + const len = nums.length; + if(len < 4) return []; + nums.sort((a, b) => a - b); + const res = []; + for(let i = 0; i < len - 3; i++) { + // 去重i + if(i > 0 && nums[i] === nums[i - 1]) continue; + for(let j = i + 1; j < len - 2; j++) { + // 去重j + if(j > i + 1 && nums[j] === nums[j - 1]) continue; + let l = j + 1, r = len - 1; + while(l < r) { + const sum = nums[i] + nums[j] + nums[l] + nums[r]; + if(sum < target) { l++; continue} + if(sum > target) { r--; continue} + res.push([nums[i], nums[j], nums[l], nums[r]]); + while(l < r && nums[l] === nums[++l]); + while(l < r && nums[r] === nums[--r]); + } + } + } + return res; +}; +``` ----------------------- diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index e84a1634..a1f1b440 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -168,10 +168,49 @@ class Solution { ``` Python: - +```python +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + if len(intervals) == 0: return intervals + intervals.sort(key=lambda x: x[0]) + result = [] + result.append(intervals[0]) + for i in range(1, len(intervals)): + last = result[-1] + if last[1] >= intervals[i][0]: + result[-1] = [last[0], max(last[1], intervals[i][1])] + else: + result.append(intervals[i]) + return result +``` Go: +```Go +func merge(intervals [][]int) [][]int { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i][0] b { return a } + return b +} +``` @@ -179,4 +218,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 5e2d48d8..39cd2ffa 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -224,6 +224,49 @@ class Solution: return matrix ``` +javaScript + +```js + +/** + * @param {number} n + * @return {number[][]} + */ +var generateMatrix = function(n) { + // new Array(n).fill(new Array(n)) + // 使用fill --> 填充的是同一个数组地址 + const res = Array.from({length: n}).map(() => new Array(n)); + let loop = n >> 1, i = 0, //循环次数 + count = 1, + startX = startY = 0; // 起始位置 + while(++i <= loop) { + // 定义行列 + let row = startX, column = startY; + // [ startY, n - i) + while(column < n - i) { + res[row][column++] = count++; + } + // [ startX, n - i) + while(row < n - i) { + res[row++][column] = count++; + } + // [n - i , startY) + while(column > startY) { + res[row][column--] = count++; + } + // [n - i , startX) + while(row > startX) { + res[row--][column] = count++; + } + startX = ++startY; + } + if(n & 1) { + res[startX][startY] = count; + } + return res; +}; +``` + ----------------------- diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index e3a6da8c..680bba83 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -249,7 +249,24 @@ Python: Go: - +```Go +func uniquePaths(m int, n int) int { + dp := make([][]int, m) + for i := range dp { + dp[i] = make([]int, n) + dp[i][0] = 1 + } + for j := 0; j < n; j++ { + dp[0][j] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + dp[i][j] = dp[i-1][j] + dp[i][j-1] + } + } + return dp[m-1][n-1] +} +``` diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1cb4164f..c40f4e2a 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -79,6 +79,35 @@ public: return result; } }; +``` +javascript代码: + +```javascript +var levelOrder = function(root) { + //二叉树的层序遍历 + let res=[],queue=[]; + queue.push(root); + if(root===null){ + return res; + } + while(queue.length!==0){ + // 记录当前层级节点数 + let length=queue.length; + //存放每一层的节点 + let curLevel=[]; + for(let i=0;inode.val?max:node.val; + node.left&&queue.push(node.left); + node.right&&queue.push(node.right); + } + //把每一层的最大值放到res数组 + res.push(max); + } + return res; +}; +``` ## 116.填充每个节点的下一个右侧节点指针 diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 93dc5fd6..139c3dae 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -233,7 +233,27 @@ class Solution { ``` Python: - +```python3 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +#递归法 +class Solution: + def sortedArrayToBST(self, nums: List[int]) -> TreeNode: + def buildaTree(left,right): + if left > right: return None #左闭右闭的区间,当区间 left > right的时候,就是空节点,当left = right的时候,不为空 + mid = left + (right - left) // 2 #保证数据不会越界 + val = nums[mid] + root = TreeNode(val) + root.left = buildaTree(left,mid - 1) + root.right = buildaTree(mid + 1,right) + return root + root = buildaTree(0,len(nums) - 1) #左闭右闭区间 + return root +``` Go: @@ -244,4 +264,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 9fca1ee0..e268c9ac 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -201,6 +201,28 @@ Python: Go: +javaScript: + +```js +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var removeElements = function(head, val) { + const ret = new ListNode(0, head); + let cur = ret; + while(cur.next) { + if(cur.next.val === val) { + cur.next = cur.next.next; + continue; + } + cur = cur.next; + } + return ret.next; +}; +``` + diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 886bbfcd..a6b3ca56 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -147,6 +147,61 @@ Python: Go: +javaScript: + +```js +/** + * @param {ListNode} head + * @return {ListNode} + */ + +// 双指针: +var reverseList = function(head) { + if(!head || !head.next) return head; + let temp = null, pre = null, cur = head; + while(cur) { + temp = cur.next; + cur.next = pre; + pre = cur; + cur = temp; + } + // temp = cur = null; + return pre; +}; + +// 递归: +var reverse = function(pre, head) { + if(!head) return pre; + const temp = head.next; + head.next = pre; + pre = head + return reverse(pre, temp); +} + +var reverseList = function(head) { + return reverse(null, head); +}; + +// 递归2 +var reverse = function(head) { + if(!head || !head.next) return head; + // 从后往前翻 + const pre = reverse(head.next); + head.next = pre.next; + pre.next = head; + return head; +} + +var reverseList = function(head) { + let cur = head; + while(cur && cur.next) { + cur = cur.next; + } + reverse(head); + return cur; +}; +``` + diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 0aaa466e..c52c5f9e 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -172,22 +172,51 @@ Python: Go: +```go +func minSubArrayLen(target int, nums []int) int { + i := 0 + l := len(nums) // 数组长度 + sum := 0 // 子数组之和 + result := l + 1 // 初始化返回长度为l+1,目的是为了判断“不存在符合条件的子数组,返回0”的情况 + for j := 0; j < l; j++ { + sum += nums[j] + for sum >= target { + subLength := j - i + 1 + if subLength < result { + result = subLength + } + sum -= nums[i] + i++ + } + } + if result == l+1 { + return 0 + } else { + return result + } +} +``` JavaScript: -``` -var minSubArrayLen = (target, nums) => { - let left = 0, right = 0,win = Infinity,sum = 0; - while(right < nums.length){ - sum += nums[right]; - while(sum >= target){ - win = right - left + 1 < win? right - left + 1 : win; - sum -= nums[left]; - left++; - } - right++; + +```js + +var minSubArrayLen = function(target, nums) { + // 长度计算一次 + const len = nums.length; + let l = r = sum = 0, + res = len + 1; // 子数组最大不会超过自身 + while(r < len) { + sum += nums[r++]; + // 窗口滑动 + while(sum >= target) { + // r始终为开区间 [l, r) + res = res < r - l ? res : r - l; + sum-=nums[l++]; + } } - return win === Infinity? 0:win; + return res > len ? 0 : res; }; ``` @@ -195,4 +224,4 @@ var minSubArrayLen = (target, nums) => { * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 3b96b4f6..968cfa4a 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -247,10 +247,100 @@ func invertTree(root *TreeNode) *TreeNode { } ``` +JavaScript: +使用递归版本的前序遍历 +```javascript +var invertTree = function(root) { + //1. 首先使用递归版本的前序遍历实现二叉树翻转 + //交换节点函数 + const inverNode=function(left,right){ + let temp=left; + left=right; + right=temp; + //需要重新给root赋值一下 + root.left=left; + root.right=right; + } + //确定递归函数的参数和返回值inverTree=function(root) + //确定终止条件 + if(root===null){ + return root; + } + //确定节点处理逻辑 交换 + inverNode(root.left,root.right); + invertTree(root.left); + invertTree(root.right); + return root; +}; +``` +使用迭代版本(统一模板))的前序遍历: +```javascript +var invertTree = function(root) { + //我们先定义节点交换函数 + const invertNode=function(root,left,right){ + let temp=left; + left=right; + right=temp; + root.left=left; + root.right=right; + } + //使用迭代方法的前序遍历 + let stack=[]; + if(root===null){ + return root; + } + stack.push(root); + while(stack.length){ + let node=stack.pop(); + if(node!==null){ + //前序遍历顺序中左右 入栈顺序是前序遍历的倒序右左中 + node.right&&stack.push(node.right); + node.left&&stack.push(node.left); + stack.push(node); + stack.push(null); + }else{ + node=stack.pop(); + //节点处理逻辑 + invertNode(node,node.left,node.right); + } + } + return root; +}; +``` +使用层序遍历: +```javascript +var invertTree = function(root) { + //我们先定义节点交换函数 + const invertNode=function(root,left,right){ + let temp=left; + left=right; + right=temp; + root.left=left; + root.right=right; + } + //使用层序遍历 + let queue=[]; + if(root===null){ + return root; + } + queue.push(root); + while(queue.length){ + let length=queue.length; + while(length--){ + let node=queue.shift(); + //节点处理逻辑 + invertNode(node,node.left,node.right); + node.left&&queue.push(node.left); + node.right&&queue.push(node.right); + } + } + return root; +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 93642de5..64e9de3f 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -247,8 +247,23 @@ class Solution { ``` Python: +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None - +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if not root: return root //中 + if root.val >p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left,p,q) //左 + elif root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right,p,q) //右 + else: return root +``` Go: @@ -258,4 +273,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 3233c6a1..a32c017e 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -263,8 +263,24 @@ class Solution { ``` Python: - - +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None +//递归 +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点 + left = self.lowestCommonAncestor(root.left,p,q) //左 + right = self.lowestCommonAncestor(root.right,p,q) //右 + if left and right: return root //中: left和right不为空,root就是最近公共节点 + elif left and not right: return left //目标节点是通过left返回的 + elif not left and right: return right //目标节点是通过right返回的 + else: return None //没找到 +``` Go: ```Go func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 10939b0f..0c75bbf9 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -140,6 +140,29 @@ func isAnagram(s string, t string) bool { } ``` +javaScript: + +```js +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function(s, t) { + if(s.length !== t.length) return false; + const resSet = new Array(26).fill(0); + const base = "a".charCodeAt(); + for(const i of s) { + resSet[i.charCodeAt() - base]++; + } + for(const i of t) { + if(!resSet[i.charCodeAt() - base]) return false; + resSet[i.charCodeAt() - base]--; + } + return true; +}; +``` + ## 相关题目 * 383.赎金信 diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 756ecc86..0260a34b 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -399,6 +399,49 @@ char ** findItinerary(char *** tickets, int ticketsSize, int* ticketsColSize, in } ``` +Javascript: +```Javascript + +var findItinerary = function(tickets) { + let result = ['JFK'] + let map = {} + + for (const tickt of tickets) { + const [from, to] = tickt + if (!map[from]) { + map[from] = [] + } + map[from].push(to) + } + + for (const city in map) { + // 对到达城市列表排序 + map[city].sort() + } + function backtracing() { + if (result.length === tickets.length + 1) { + return true + } + if (!map[result[result.length - 1]] || !map[result[result.length - 1]].length) { + return false + } + for(let i = 0 ; i < map[result[result.length - 1]].length; i++) { + let city = map[result[result.length - 1]][i] + // 删除已走过航线,防止死循环 + map[result[result.length - 1]].splice(i, 1) + result.push(city) + if (backtracing()) { + return true + } + result.pop() + map[result[result.length - 1]].splice(i, 0, city) + } + } + backtracing() + return result +}; + +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 8a6b0a40..820cbaa2 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -122,6 +122,34 @@ Python: Go: +javaScript: + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function(nums1, nums2) { + // 根据数组大小交换操作的数组 + if(nums1.length < nums2.length) { + const _ = nums1; + nums1 = nums2; + nums2 = _; + } + const nums1Set = new Set(nums1); + const resSet = new Set(); + // for(const n of nums2) { + // nums1Set.has(n) && resSet.add(n); + // } + // 循环 比 迭代器快 + for(let i = nums2.length - 1; i >= 0; i--) { + nums1Set.has(nums2[i]) && resSet.add(nums2[i]); + } + return Array.from(resSet); +}; +``` + ## 相关题目 diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 527945fa..755910f9 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -136,7 +136,7 @@ class Solution { ``` Python: -``` +```py class Solution(object): def canConstruct(self, ransomNote, magazine): """ @@ -167,6 +167,28 @@ class Solution(object): Go: +javaScript: + +```js +/** + * @param {string} ransomNote + * @param {string} magazine + * @return {boolean} + */ +var canConstruct = function(ransomNote, magazine) { + const strArr = new Array(26).fill(0), + base = "a".charCodeAt(); + for(const s of magazine) { + strArr[s.charCodeAt() - base]++; + } + for(const s of ransomNote) { + const index = s.charCodeAt() - base; + if(!strArr[index]) return false; + strArr[index]--; + } + return true; +}; +``` diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 4341f3b8..540a82e3 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -212,7 +212,19 @@ class Solution { ``` Python: - +```python +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + if len(intervals) == 0: return 0 + intervals.sort(key=lambda x: x[1]) + count = 1 # 记录非交叉区间的个数 + end = intervals[0][1] # 记录区间分割点 + for i in range(1, len(intervals)): + if end <= intervals[i][0]: + count += 1 + end = intervals[i][1] + return len(intervals) - count +``` Go: @@ -223,4 +235,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 604fb376..2cac8f87 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -281,7 +281,43 @@ class Solution { ``` Python: - +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def deleteNode(self, root: TreeNode, key: int) -> TreeNode: + if not root: return root #第一种情况:没找到删除的节点,遍历到空节点直接返回了 + if root.val == key: + if not root.left and not root.right: #第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点 + del root + return None + if not root.left and root.right: #第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点 + tmp = root + root = root.right + del tmp + return root + if root.left and not root.right: #第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点 + tmp = root + root = root.left + del tmp + return root + else: #第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置 + v = root.right + while v.left: + v = v.left + v.left = root.left + tmp = root + root = root.right + del tmp + return root + if root.val > key: root.left = self.deleteNode(root.left,key) #左递归 + if root.val < key: root.right = self.deleteNode(root.right,key) #右递归 + return root +``` Go: ```Go @@ -330,4 +366,4 @@ func deleteNode1(root *TreeNode)*TreeNode{ * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index f62fb153..45c94a01 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -70,7 +70,7 @@ 其实都可以!只不过对应的遍历顺序不同,我就按照气球的起始位置排序了。 -既然按照其实位置排序,那么就从前向后遍历气球数组,靠左尽可能让气球重复。 +既然按照起始位置排序,那么就从前向后遍历气球数组,靠左尽可能让气球重复。 从前向后遍历遇到重叠的气球了怎么办? @@ -167,7 +167,19 @@ class Solution { ``` Python: - +```python +class Solution: + def findMinArrowShots(self, points: List[List[int]]) -> int: + if len(points) == 0: return 0 + points.sort(key=lambda x: x[0]) + result = 1 + for i in range(1, len(points)): + if points[i][0] > points[i - 1][1]: # 气球i和气球i-1不挨着,注意这里不是>= + result += 1 + else: + points[i][1] = min(points[i - 1][1], points[i][1]) # 更新重叠气球最小右边界 + return result +``` Go: @@ -178,4 +190,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index ad928a3f..28db6a50 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -155,6 +155,38 @@ class Solution(object): Go: +javaScript: + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @param {number[]} nums3 + * @param {number[]} nums4 + * @return {number} + */ +var fourSumCount = function(nums1, nums2, nums3, nums4) { + const twoSumMap = new Map(); + let count = 0; + + for(const n1 of nums1) { + for(const n2 of nums2) { + const sum = n1 + n2; + twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1) + } + } + + for(const n3 of nums3) { + for(const n4 of nums4) { + const sum = n3 + n4; + count += (twoSumMap.get(0 - sum) || 0) + } + } + + return count; +}; +``` + diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 1782c88c..65d9b4e2 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -225,7 +225,7 @@ public: 是的,如果仅仅是求个数的话,就可以用dp,但[回溯算法:39. 组合总和](https://mp.weixin.qq.com/s/FLg8G6EjVcxBjwCbzpACPw)要求的是把所有组合列出来,还是要使用回溯法爆搜的。 -本地还是有点难度,大家也可以记住,在求装满背包有几种方法的情况下,递推公式一般为: +本题还是有点难度,大家也可以记住,在求装满背包有几种方法的情况下,递推公式一般为: ``` dp[j] += dp[j - nums[i]]; @@ -272,4 +272,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 385ce2f1..0ddd8b0c 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -394,8 +394,39 @@ class Solution { ``` Python: - - +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +//递归法 +class Solution: + def findMode(self, root: TreeNode) -> List[int]: + if not root: return + self.pre = root + self.count = 0 //统计频率 + self.countMax = 0 //最大频率 + self.res = [] + def findNumber(root): + if not root: return None // 第一个节点 + findNumber(root.left) //左 + if self.pre.val == root.val: //中: 与前一个节点数值相同 + self.count += 1 + else: // 与前一个节点数值不同 + self.pre = root + self.count = 1 + if self.count > self.countMax: // 如果计数大于最大值频率 + self.countMax = self.count // 更新最大频率 + self.res = [root.val] //更新res + elif self.count == self.countMax: // 如果和最大值相同,放进res中 + self.res.append(root.val) + findNumber(root.right) //右 + return + findNumber(root) + return self.res +``` Go: @@ -405,4 +436,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 112c96f9..5afcd6b8 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -207,6 +207,19 @@ class Solution: ``` Go: +```Go +func fib(n int) int { + if n < 2 { + return n + } + a, b, c := 0, 1, 0 + for i := 1; i < n; i++ { + c = a + b + a, b = b, c + } + return c +} +``` diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 209c989b..cc19bb30 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -196,8 +196,26 @@ class Solution { ``` Python: - - +```python3 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +#递归法 +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + def buildalist(root): + if not root: return None + buildalist(root.right) #右中左遍历 + root.val += self.pre + self.pre = root.val + buildalist(root.left) + self.pre = 0 #记录前一个节点的数值 + buildalist(root) + return root +``` Go: @@ -207,4 +225,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 0a92ac8b..6171613f 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -134,6 +134,36 @@ class Solution { ``` Python: +```python + +class Solution(object): + def reverseStr(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + from functools import reduce + # turn s into a list + s = list(s) + + # another way to simply use a[::-1], but i feel this is easier to understand + def reverse(s): + left, right = 0, len(s) - 1 + while left < right: + s[left], s[right] = s[right], s[left] + left += 1 + right -= 1 + return s + + # make sure we reverse each 2k elements + for i in range(0, len(s), 2*k): + s[i:(i+k)] = reverse(s[i:(i+k)]) + + # combine list into str. + return reduce(lambda a, b: a+b, s) + +``` Go: diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 8b9e1f6d..5c839b6c 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -265,8 +265,24 @@ class Solution { ``` Python: - - +```python3 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: + if not root: return root + if root.val < low: + return self.trimBST(root.right,low,high) // 寻找符合区间[low, high]的节点 + if root.val > high: + return self.trimBST(root.left,low,high) // 寻找符合区间[low, high]的节点 + root.left = self.trimBST(root.left,low,high) // root->left接入符合条件的左孩子 + root.right = self.trimBST(root.right,low,high) // root->right接入符合条件的右孩子 + return root +``` Go: @@ -276,4 +292,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 76d4a2af..c97fd36e 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -254,6 +254,43 @@ func search(nums []int, target int) int { } ``` +javaScript + +```js + +// (版本一)左闭右闭区间 + +var search = function(nums, target) { + let l = 0, r = nums.length - 1; + // 区间 [l, r] + while(l <= r) { + let mid = (l + r) >> 1; + if(nums[mid] === target) return mid; + let isSmall = nums[mid] < target; + l = isSmall ? mid + 1 : l; + r = isSmall ? r : mid - 1; + } + return -1; +}; + +// (版本二)左闭右开区间 + +var search = function(nums, target) { + let l = 0, r = nums.length; + // 区间 [l, r) + while(l < r) { + let mid = (l + r) >> 1; + if(nums[mid] === target) return mid; + let isSmall = nums[mid] < target; + l = isSmall ? mid + 1 : l; + // 所以 mid 不会被取到 + r = isSmall ? r : mid; + } + return -1; +}; + +``` + diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 86cf623b..a4f4d8d3 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -393,6 +393,142 @@ class MyLinkedList: Go: +javaScript: + +```js + +class LinkNode { + constructor(val, next) { + this.val = val; + this.next = next; + } +} + +/** + * Initialize your data structure here. + * 单链表 储存头尾节点 和 节点数量 + */ +var MyLinkedList = function() { + this._size = 0; + this._tail = null; + this._head = null; +}; + +/** + * Get the value of the index-th node in the linked list. If the index is invalid, return -1. + * @param {number} index + * @return {number} + */ +MyLinkedList.prototype.getNode = function(index) { + if(index < 0 || index >= this._size) return null; + // 创建虚拟头节点 + let cur = new LinkNode(0, this._head); + // 0 -> head + while(index-- >= 0) { + cur = cur.next; + } + return cur; +}; +MyLinkedList.prototype.get = function(index) { + if(index < 0 || index >= this._size) return -1; + // 获取当前节点 + return this.getNode(index).val; +}; + +/** + * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtHead = function(val) { + const node = new LinkNode(val, this._head); + this._head = node; + this._size++; + if(!this._tail) { + this._tail = node; + } +}; + +/** + * Append a node of value val to the last element of the linked list. + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtTail = function(val) { + const node = new LinkNode(val, null); + this._size++; + if(this._tail) { + this._tail.next = node; + this._tail = node; + return; + } + this._tail = node; + this._head = node; +}; + +/** + * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. + * @param {number} index + * @param {number} val + * @return {void} + */ +MyLinkedList.prototype.addAtIndex = function(index, val) { + if(index > this._size) return; + if(index <= 0) { + this.addAtHead(val); + return; + } + if(index === this._size) { + this.addAtTail(val); + return; + } + // 获取目标节点的上一个的节点 + const node = this.getNode(index - 1); + node.next = new LinkNode(val, node.next); + this._size++; +}; + +/** + * Delete the index-th node in the linked list, if the index is valid. + * @param {number} index + * @return {void} + */ +MyLinkedList.prototype.deleteAtIndex = function(index) { + if(index < 0 || index >= this._size) return; + if(index === 0) { + this._head = this._head.next; + this._size--; + return; + } + // 获取目标节点的上一个的节点 + const node = this.getNode(index - 1); + node.next = node.next.next; + // 处理尾节点 + if(index === this._size - 1) { + this._tail = node; + } + this._size--; +}; + +// MyLinkedList.prototype.out = function() { +// let cur = this._head; +// const res = []; +// while(cur) { +// res.push(cur.val); +// cur = cur.next; +// } +// }; +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ +``` + diff --git a/problems/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index 99f01197..f4295da2 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -199,7 +199,21 @@ class Solution { // 动态规划 Python: - +```python +class Solution: # 贪心思路 + def maxProfit(self, prices: List[int], fee: int) -> int: + result = 0 + minPrice = prices[0] + for i in range(1, len(prices)): + if prices[i] < minPrice: + minPrice = prices[i] + elif prices[i] >= minPrice and prices[i] <= minPrice + fee: + continue + else: + result += prices[i] - minPrice - fee + minPrice = prices[i] - fee + return result +``` Go: diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index dc136028..4324a0bc 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -8,6 +8,7 @@ ## 738.单调递增的数字 +题目链接: https://leetcode-cn.com/problems/monotone-increasing-digits/ 给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。 @@ -30,7 +31,7 @@ ## 暴力解法 -题意很简单,那么首先想的就是暴力解法了,来我提大家暴力一波,结果自然是超时! +题意很简单,那么首先想的就是暴力解法了,来我替大家暴力一波,结果自然是超时! 代码如下: ```C++ @@ -146,7 +147,19 @@ class Solution { Python: - +```python +class Solution: + def monotoneIncreasingDigits(self, n: int) -> int: + strNum = list(str(n)) + flag = len(strNum) + for i in range(len(strNum) - 1, 0, -1): + if int(strNum[i]) < int(strNum[i - 1]): + strNum[i - 1] = str(int(strNum[i - 1]) - 1) + flag = i + for i in range(flag, len(strNum)): + strNum[i] = '9' + return int("".join(strNum)) +``` Go: @@ -157,4 +170,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +
diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index b8158205..aff56208 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -228,7 +228,23 @@ Python: Go: +```Go +func minCostClimbingStairs(cost []int) int { + dp := make([]int, len(cost)) + dp[0], dp[1] = cost[0], cost[1] + for i := 2; i < len(cost); i++ { + dp[i] = min(dp[i-1], dp[i-2]) + cost[i] + } + return min(dp[len(cost)-1], dp[len(cost)-2]) +} +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md index c1474280..a6ca0ea0 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -108,7 +108,23 @@ class Solution { ``` Python: +```python +class Solution: + def partitionLabels(self, s: str) -> List[int]: + hash = [0] * 26 + for i in range(len(s)): + hash[ord(s[i]) - ord('a')] = i + result = [] + left = 0 + right = 0 + for i in range(len(s)): + right = max(right, hash[ord(s[i]) - ord('a')]) + if i == right: + result.append(right - left + 1) + left = i + 1 + return result +``` Go: diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 607a4ccf..32a29c2a 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -122,6 +122,8 @@ public: Java: + +使用 Deque 作为堆栈 ```Java class Solution { public String removeDuplicates(String S) { @@ -144,6 +146,30 @@ class Solution { } } ``` +拿字符串直接作为栈,省去了栈还要转为字符串的操作。 +```Java +class Solution { + public String removeDuplicates(String s) { + // 将 res 当做栈 + StringBuffer res = new StringBuffer(); + // top为 res 的长度 + int top = -1; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + // 当 top > 0,即栈中有字符时,当前字符如果和栈中字符相等,弹出栈顶字符,同时 top-- + if (top >= 0 && res.charAt(top) == c) { + res.deleteCharAt(top); + top--; + // 否则,将该字符 入栈,同时top++ + } else { + res.append(c); + top++; + } + } + return res.toString(); + } +} +``` Python: ```python3 diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index bc91eca0..bf3e83f4 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -242,7 +242,137 @@ Python: Go: +> 前序遍历统一迭代法 +```GO + /** + type Element struct { + // 元素保管的值 + Value interface{} + // 内含隐藏或非导出字段 +} + +func (l *List) Back() *Element +前序遍历:中左右 +压栈顺序:右左中 + **/ +func preorderTraversal(root *TreeNode) []int { + if root == nil { + return nil + } + var stack = list.New()//栈 + res:=[]int{}//结果集 + stack.PushBack(root) + var node *TreeNode + for stack.Len()>0{ + e := stack.Back() + stack.Remove(e)//弹出元素 + if e.Value==nil{// 如果为空,则表明是需要处理中间节点 + e=stack.Back()//弹出元素(即中间节点) + stack.Remove(e)//删除中间节点 + node=e.Value.(*TreeNode) + res=append(res,node.Val)//将中间节点加入到结果集中 + continue//继续弹出栈中下一个节点 + } + node = e.Value.(*TreeNode) + //压栈顺序:右左中 + if node.Right!=nil{ + stack.PushBack(node.Right) + } + if node.Left!=nil{ + stack.PushBack(node.Left) + } + stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符 + stack.PushBack(nil) + } + return res + +} +``` + +> 中序遍历统一迭代法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + //中序遍历:左中右 + //压栈顺序:右中左 +func inorderTraversal(root *TreeNode) []int { + if root==nil{ + return nil + } + stack:=list.New()//栈 + res:=[]int{}//结果集 + stack.PushBack(root) + var node *TreeNode + for stack.Len()>0{ + e := stack.Back() + stack.Remove(e) + if e.Value==nil{// 如果为空,则表明是需要处理中间节点 + e=stack.Back()//弹出元素(即中间节点) + stack.Remove(e)//删除中间节点 + node=e.Value.(*TreeNode) + res=append(res,node.Val)//将中间节点加入到结果集中 + continue//继续弹出栈中下一个节点 + } + node = e.Value.(*TreeNode) + //压栈顺序:右中左 + if node.Right!=nil{ + stack.PushBack(node.Right) + } + stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符 + stack.PushBack(nil) + if node.Left!=nil{ + stack.PushBack(node.Left) + } + } + return res +} +``` + +> 后序遍历统一迭代法 + +```go +//后续遍历:左右中 +//压栈顺序:中右左 +func postorderTraversal(root *TreeNode) []int { + if root == nil { + return nil + } + var stack = list.New()//栈 + res:=[]int{}//结果集 + stack.PushBack(root) + var node *TreeNode + for stack.Len()>0{ + e := stack.Back() + stack.Remove(e) + if e.Value==nil{// 如果为空,则表明是需要处理中间节点 + e=stack.Back()//弹出元素(即中间节点) + stack.Remove(e)//删除中间节点 + node=e.Value.(*TreeNode) + res=append(res,node.Val)//将中间节点加入到结果集中 + continue//继续弹出栈中下一个节点 + } + node = e.Value.(*TreeNode) + //压栈顺序:中右左 + stack.PushBack(node)//中间节点压栈后再压入nil作为中间节点的标志符 + stack.PushBack(nil) + if node.Right!=nil{ + stack.PushBack(node.Right) + } + if node.Left!=nil{ + stack.PushBack(node.Left) + } + } + return res +} +``` diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 2d571294..e5279ec0 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -306,6 +306,59 @@ var postorderTraversal = function(root, res = []) { return res; }; ``` +Javascript版本: + +前序遍历: +```Javascript +var preorderTraversal = function(root) { + let res=[]; + const dfs=function(root){ + if(root===null)return ; + //先序遍历所以从父节点开始 + res.push(root.val); + //递归左子树 + dfs(root.left); + //递归右子树 + dfs(root.right); + } + //只使用一个参数 使用闭包进行存储结果 + dfs(root); + return res; +}; +``` +中序遍历 +```javascript +var inorderTraversal = function(root) { + let res=[]; + const dfs=function(root){ + if(root===null){ + return ; + } + dfs(root.left); + res.push(root.val); + dfs(root.right); + } + dfs(root); + return res; +}; +``` + +后序遍历 +```javascript +var postorderTraversal = function(root) { + let res=[]; + const dfs=function(root){ + if(root===null){ + return ; + } + dfs(root.left); + dfs(root.right); + res.push(root.val); + } + dfs(root); + return res; +}; +``` diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 3e9ab11f..9bd639aa 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -96,10 +96,27 @@ public: ## 其他语言版本 - Java: - - +```java +class Solution { + public String reverseLeftWords(String s, int n) { + int len=s.length(); + StringBuilder sb=new StringBuilder(s); + reverseString(sb,0,n-1); + reverseString(sb,n,len-1); + return sb.reverse().toString(); + } + public void reverseString(StringBuilder sb, int start, int end) { + while (start < end) { + char temp = sb.charAt(start); + sb.setCharAt(start, sb.charAt(end)); + sb.setCharAt(end, temp); + start++; + end--; + } + } +} +``` Python: diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 493438d7..6bc331b5 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -155,6 +155,42 @@ Python: Go: +javaScript: + +```js +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ +var getListLen = function(head) { + let len = 0, cur = head; + while(cur) { + len++; + cur = cur.next; + } + return len; +} +var getIntersectionNode = function(headA, headB) { + let curA = headA,curB = headB, + lenA = getListLen(headA), + lenB = getListLen(headB); + if(lenA < lenB) { + [curA, curB] = [curB, curA]; + [lenA, lenB] = [lenB, lenA]; + } + let i = lenA - lenB; + while(i-- > 0) { + curA = curA.next + } + while(curA && curA !== curB) { + curA = curA.next; + curB = curB.next; + } + return curA; +}; +``` +