From ee9afc13e81a8dbf8a653c406b6819f3d4353d16 Mon Sep 17 00:00:00 2001 From: weijiew <49638002+weijiew@users.noreply.github.com> Date: Wed, 12 May 2021 09:51:38 +0800 Subject: [PATCH 001/177] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 7dc7f7d7..8055d481 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -91,7 +91,7 @@ leetcode上没有纯01背包的问题,都是01背包应用方面的题目, **关于初始化,一定要和dp数组的定义吻合,否则到递推公式的时候就会越来越乱**。 -首先从dp[i][j]的定义触发,如果背包容量j为0的话,即dp[i][0],无论是选取哪些物品,背包价值总和一定为0。如图: +首先从dp[i][j]的定义出发,如果背包容量j为0的话,即dp[i][0],无论是选取哪些物品,背包价值总和一定为0。如图: ![动态规划-背包问题2](https://img-blog.csdnimg.cn/2021011010304192.png) From 825cdd5359a0c7730d63259e58a786cd07ec67a4 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 10:50:11 +0800 Subject: [PATCH 002/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0015.三数之和 --- problems/0015.三数之和.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 0bd683a8..1dabe885 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -178,7 +178,44 @@ public: Java: +```Java +class Solution { + public List> threeSum(int[] nums) { + List> result = new ArrayList<>(); + Arrays.sort(nums); + for (int i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + return result; + } + + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + + int left = i + 1; + int right = nums.length - 1; + while (right > left) { + int sum = nums[i] + nums[left] + nums[right]; + if (sum > 0) { + right--; + } else if (sum < 0) { + left++; + } else { + result.add(Arrays.asList(nums[i], nums[left], nums[right])); + + while (right > left && nums[right] == nums[right - 1]) right--; + while (right > left && nums[left] == nums[left + 1]) left++; + + right--; + left++; + } + } + } + return result; + } +} +``` Python: From 791994b233eb5a402fb75b36eef5003867546db6 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 10:59:24 +0800 Subject: [PATCH 003/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00018.=E5=9B=9B?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0018.四数之和 Java版本 --- problems/0018.四数之和.md | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 72f8cee5..ff441bf7 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -121,7 +121,48 @@ public: Java: +```Java +class Solution { + public List> fourSum(int[] nums, int target) { + List> result = new ArrayList<>(); + Arrays.sort(nums); + + for (int i = 0; i < nums.length; i++) { + if (i > 0 && nums[i - 1] == nums[i]) { + continue; + } + + for (int j = i + 1; j < nums.length; j++) { + + if (j > i + 1 && nums[j - 1] == nums[j]) { + continue; + } + + int left = j + 1; + int right = nums.length - 1; + while (right > left) { + int sum = nums[i] + nums[j] + nums[left] + nums[right]; + if (sum > target) { + right--; + } else if (sum < target) { + left++; + } else { + result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); + + while (right > left && nums[right] == nums[right - 1]) right--; + while (right > left && nums[left] == nums[left + 1]) left++; + + left++; + right--; + } + } + } + } + return result; + } +} +``` Python: From d0e032dc9be90d8f707c760847803e94ee85fd29 Mon Sep 17 00:00:00 2001 From: zjd <12321619+realpeanut@users.noreply.github.com> Date: Wed, 12 May 2021 10:59:58 +0800 Subject: [PATCH 004/177] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 726fc7a8..2230d404 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -46,7 +46,7 @@ ### 二叉搜索树 -前面介绍的书,都没有数值的,而二叉搜索树是有数值的了,**二叉搜索树是一个有序树**。 +前面介绍的树,都没有数值的,而二叉搜索树是有数值的了,**二叉搜索树是一个有序树**。 * 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; @@ -164,7 +164,7 @@ struct TreeNode { 大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子. -这里要提醒大家要注意二叉树节点定义的书写方式。 +这里要提醒大家要注意二叉树节点定义的写方式。 **在现场面试的时候 面试官可能要求手写代码,所以数据结构的定义以及简单逻辑的代码一定要锻炼白纸写出来。** @@ -193,7 +193,13 @@ Python: Go: - +``` +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} +``` From 309a1cf9ad9c1b0c62833d822d20531268b7b3e8 Mon Sep 17 00:00:00 2001 From: zjd <12321619+realpeanut@users.noreply.github.com> Date: Wed, 12 May 2021 11:11:52 +0800 Subject: [PATCH 005/177] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 2230d404..60e65c69 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -164,7 +164,7 @@ struct TreeNode { 大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子. -这里要提醒大家要注意二叉树节点定义的写方式。 +这里要提醒大家要注意二叉树节点定义的书写方式。 **在现场面试的时候 面试官可能要求手写代码,所以数据结构的定义以及简单逻辑的代码一定要锻炼白纸写出来。** @@ -195,9 +195,9 @@ Python: Go: ``` type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode + Val int + Left *TreeNode + Right *TreeNode } ``` From 60c1908c4d89b3bc9c0c0ce5ab7acfe6100f4412 Mon Sep 17 00:00:00 2001 From: zjd <12321619+realpeanut@users.noreply.github.com> Date: Wed, 12 May 2021 11:40:40 +0800 Subject: [PATCH 006/177] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E9=80=92?= =?UTF-8?q?=E5=BD=92=E9=81=8D=E5=8E=86=E5=A2=9E=E5=8A=A0golang=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 6c005191..bd3a9e1c 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -122,6 +122,58 @@ Python: Go: +前序遍历: +``` +func PreorderTraversal(root *TreeNode) (res []int) { + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return + } + res = append(res,node.Val) + traversal(node.Left) + traversal(node.Right) + } + traversal(root) + return res +} + +``` +中序遍历: + +``` +func InorderTraversal(root *TreeNode) (res []int) { + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return + } + traversal(node.Left) + res = append(res,node.Val) + traversal(node.Right) + } + traversal(root) + return res +} +``` +后序遍历: + +``` +func PostorderTraversal(root *TreeNode) (res []int) { + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return + } + traversal(node.Left) + traversal(node.Right) + res = append(res,node.Val) + } + traversal(root) + return res +} +``` + From 08efaac9f722afa677a40b5d7509d18cd07994c9 Mon Sep 17 00:00:00 2001 From: zjd <12321619+realpeanut@users.noreply.github.com> Date: Wed, 12 May 2021 11:44:30 +0800 Subject: [PATCH 007/177] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 60 ++++++++++++++-------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index bd3a9e1c..02d4b060 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -125,17 +125,17 @@ Go: 前序遍历: ``` func PreorderTraversal(root *TreeNode) (res []int) { - var traversal func(node *TreeNode) - traversal = func(node *TreeNode) { - if node == nil { - return - } - res = append(res,node.Val) - traversal(node.Left) - traversal(node.Right) + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return } - traversal(root) - return res + res = append(res,node.Val) + traversal(node.Left) + traversal(node.Right) + } + traversal(root) + return res } ``` @@ -143,34 +143,34 @@ func PreorderTraversal(root *TreeNode) (res []int) { ``` func InorderTraversal(root *TreeNode) (res []int) { - var traversal func(node *TreeNode) - traversal = func(node *TreeNode) { - if node == nil { - return - } - traversal(node.Left) - res = append(res,node.Val) - traversal(node.Right) + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return } - traversal(root) - return res + traversal(node.Left) + res = append(res,node.Val) + traversal(node.Right) + } + traversal(root) + return res } ``` 后序遍历: ``` func PostorderTraversal(root *TreeNode) (res []int) { - var traversal func(node *TreeNode) - traversal = func(node *TreeNode) { - if node == nil { - return - } - traversal(node.Left) - traversal(node.Right) - res = append(res,node.Val) + var traversal func(node *TreeNode) + traversal = func(node *TreeNode) { + if node == nil { + return } - traversal(root) - return res + traversal(node.Left) + traversal(node.Right) + res = append(res,node.Val) + } + traversal(root) + return res } ``` From a1d74a5419cc3121eeed213e18fdcbfd6fd9210c Mon Sep 17 00:00:00 2001 From: TCP404 Date: Wed, 12 May 2021 13:04:01 +0800 Subject: [PATCH 008/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00001.=E4=B8=A4?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 7425ff4f..6c9d99dd 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -109,6 +109,19 @@ Python: Go: +```go +func twoSum(nums []int, target int) []int { + for k1, _ := range nums { + for k2 := k1 + 1; k2 < len(nums); k2++ { + if target == nums[k1] + nums[k2] { + return []int{k1, k2} + } + } + } + return []int{} +} +``` + @@ -116,4 +129,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 From 74ba60e18a0a5951f0b96011c12095a97387b685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=B2=E4=BB=8E=E4=BB=8A=E5=A4=9C=E7=99=BD?= <1101131319@qq.com> Date: Wed, 12 May 2021 13:15:11 +0800 Subject: [PATCH 009/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00027.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0.md=20JavaScript=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 3772d754..5cfdb68d 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -131,7 +131,20 @@ Python: Go: - +JavaScript: +``` +//时间复杂度O(n) +//空间复杂度O(1) +var removeElement = (nums, val) => { + let k = 0; + for(let i = 0;i < nums.length;i++){ + if(nums[i] != val){ + nums[k++] = nums[i] + } + } + return k; +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From 24ba15df6d09bb8a4ae5c5dabc2fe399f883a228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=B2=E4=BB=8E=E4=BB=8A=E5=A4=9C=E7=99=BD?= <1101131319@qq.com> Date: Wed, 12 May 2021 13:18:00 +0800 Subject: [PATCH 010/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00209.=E9=95=BF?= =?UTF-8?q?=E5=BA=A6=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?= =?UTF-8?q?=20JavaScript=E7=89=88=E6=9C=AC=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0209.长度最小的子数组.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index c3937d7b..1b00c4e3 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -156,7 +156,22 @@ Python: Go: - +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++; + } + return win === Infinity? 0:win; +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From 259f16779a75661a082c7dae378c534c3a29146d Mon Sep 17 00:00:00 2001 From: Webary <813577991@qq.com> Date: Wed, 12 May 2021 13:22:46 +0800 Subject: [PATCH 011/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00020.=E6=9C=89?= =?UTF-8?q?=E6=95=88=E7=9A=84=E6=8B=AC=E5=8F=B7Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index e8784397..f2d78ade 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -141,7 +141,20 @@ Java: Python: - +```python3 +class Solution: + def isValid(self, s: str) -> bool: + stack = [] # 保存还未匹配的左括号 + mapping = {")": "(", "]": "[", "}": "{"} + for i in s: + if i in "([{": # 当前是左括号,则入栈 + stack.append(i) + elif stack and stack[-1] == mapping[i]: # 当前是配对的右括号则出栈 + stack.pop() + else: # 不是匹配的右括号或者没有左括号与之匹配,则返回false + return False + return stack == [] # 最后必须正好把左括号匹配完 +``` Go: From b62eb30a7195469a8a6a5f90559016d266376867 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 13:23:27 +0800 Subject: [PATCH 012/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0015.三数之和 Java版本 --- problems/0015.三数之和.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 1dabe885..55e22887 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -207,7 +207,7 @@ class Solution { while (right > left && nums[right] == nums[right - 1]) right--; while (right > left && nums[left] == nums[left + 1]) left++; - right--; + right--; left++; } } From 2bd7ab27bc2f1ab5f2e89e070c8c2c56a7c31a64 Mon Sep 17 00:00:00 2001 From: faiz-lab Date: Wed, 12 May 2021 13:40:20 +0800 Subject: [PATCH 013/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00101.=E5=AF=B9?= =?UTF-8?q?=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91=20JavaScript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 85daa229..561d0470 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -263,6 +263,21 @@ Python: Go: +JavaScript +```javascript +var isSymmetric = function(root) { + return check(root, root) +}; + +const check = (leftPtr, rightPtr) => { + // 如果只有根节点,返回true + if (!leftPtr && !rightPtr) return true + // 如果左右节点只存在一个,则返回false + if (!leftPtr || !rightPtr) return false + + return leftPtr.val === rightPtr.val && check(leftPtr.left, rightPtr.right) && check(leftPtr.right, rightPtr.left) +} +``` ----------------------- From 1f609be3b329654b99194591b3e0c132b3d5ad58 Mon Sep 17 00:00:00 2001 From: Tiansheng Sui Date: Tue, 11 May 2021 23:38:24 -0700 Subject: [PATCH 014/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BEPython=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 9261e135..bb013d95 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -151,6 +151,22 @@ Java: Python: +```python3 +class Solution: + def search(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + + while left <= right: + middle = (left + right) // 2 + + if nums[middle] < target: + left = middle + 1 + elif nums[middle] > target: + right = middle - 1 + else: + return middle + return -1 +``` Go: From 90b60a600542c17f28b491f4640ff615f654eb01 Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 14:53:46 +0800 Subject: [PATCH 015/177] =?UTF-8?q?0035.=E6=90=9C=E7=B4=A2=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E4=BD=8D=E7=BD=AE=E5=92=8CJava=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 5bd3b553..12fe714e 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -205,9 +205,36 @@ public: ## 其他语言版本 - Java: +```java +class Solution { + public int searchInsert(int[] nums, int target) { + int n = nums.length; + + // 定义target在左闭右闭的区间里,[low, high] + int low = 0; + int high = n - 1; + + while (low <= high) { // 当low==high,区间[low, high]依然有效 + int mid = low + (high - low) / 2; // 防止溢出 + if (nums[mid] > target) { + high = mid - 1; // target 在左区间,所以[low, mid - 1] + } else if (nums[mid] < target) { + low = mid + 1; // target 在右区间,所以[mid + 1, high] + } else { + // 1. 目标值等于数组中某一个元素 return mid; + return mid; + } + } + // 2.目标值在数组所有元素之前 3.目标值插入数组中 4.目标值在数组所有元素之后 return right + 1; + return high + 1; + } +} +``` + + + Python: From 8cdefe9f92362f71a1beffa46ff805ae2a95a4fb Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 14:56:48 +0800 Subject: [PATCH 016/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00035.=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AE=E5=92=8CJava?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 12fe714e..c351e365 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -212,7 +212,7 @@ class Solution { public int searchInsert(int[] nums, int target) { int n = nums.length; - // 定义target在左闭右闭的区间里,[low, high] + // 定义target在左闭右闭的区间,[low, high] int low = 0; int high = n - 1; From 04bb63da12b4bd0ba9c38a4ca12e6334f1c155c7 Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Wed, 12 May 2021 15:41:32 +0800 Subject: [PATCH 017/177] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加27. 移除元素 go版本 --- problems/0242.有效的字母异位词.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 9c492431..463a793f 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -91,8 +91,19 @@ Python: Go: - - +```go +func removeElement(nums []int, val int) int { + length:=len(nums) + res:=0 + for i:=0;i Date: Wed, 12 May 2021 15:44:55 +0800 Subject: [PATCH 018/177] =?UTF-8?q?Update=200027.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0027.移除元素 go版本 --- problems/0027.移除元素.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 5cfdb68d..144cd5be 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -129,7 +129,19 @@ Python: Go: - +```go +func removeElement(nums []int, val int) int { + length:=len(nums) + res:=0 + for i:=0;i Date: Wed, 12 May 2021 15:48:38 +0800 Subject: [PATCH 019/177] =?UTF-8?q?Update=200242.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0242.有效的字母异位词 go版本 --- problems/0242.有效的字母异位词.md | 26 ++++++++++++++++------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 463a793f..be553c5a 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -92,16 +92,26 @@ Python: Go: ```go -func removeElement(nums []int, val int) int { - length:=len(nums) - res:=0 - for i:=0;i=0&&ok{ + exists[s[i]]=v+1 + }else{ + exists[s[i]]=1 } } - return res + for i:=0;i=1&&ok{ + exists[t[i]]=v-1 + }else{ + return false + } + } + return true } ``` From 612d400c36c28ea9917ac2b13b23f7fed7d73420 Mon Sep 17 00:00:00 2001 From: doo0301 Date: Wed, 12 May 2021 15:21:02 +0800 Subject: [PATCH 020/177] =?UTF-8?q?0102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md=20=20Java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index cfbe09f3..8c34d415 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -419,6 +419,36 @@ public: Java: +```Java + +class Solution { + public List> resList=new ArrayList>(); + public List> levelOrder(TreeNode root) { + checkFun01(root,0); + + return resList; + } + + //递归方式 + public void checkFun01(TreeNode node,Integer deep){ + if(node==null) return; + deep++; + + if(resList.size() item=new ArrayList(); + resList.add(item); + } + resList.get(deep-1).add(node.val); + + + checkFun01(node.left,deep); + checkFun01(node.right,deep); + } + + +``` + Python: From a40b5094a93ed10bbec05e96354e570bc4267f19 Mon Sep 17 00:00:00 2001 From: HermanZzz Date: Wed, 12 May 2021 15:59:24 +0800 Subject: [PATCH 021/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00112.=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=80=BB=E5=92=8C=20JavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 40df1e7a..51ee0872 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -312,6 +312,37 @@ Python: Go: +JavaScript: + +```javascript +/** + * @param {TreeNode} root + * @param {number} targetSum + * @return {boolean} + */ +let hasPathSum = function (root, targetSum) { + const traversal = (node, cnt) => { + // 遇到叶子节点,并且计数为0 + if (cnt === 0 && !node.left && !node.right) return true; + // 遇到叶子节点而没有找到合适的边(计数不为0),直接返回 + if (!node.left && !node.right) return false; + + // 左(空节点不遍历).遇到叶子节点返回true,则直接返回true + if (node.left && traversal(node.left, cnt - node.left.val)) return true; + // 右(空节点不遍历) + if (node.right && traversal(node.right, cnt - node.right.val)) return true; + return false; + }; + if (!root) return false; + return traversal(root, targetSum - root.val); + + // 精简代码: + // if (!root) return false; + // if (!root.left && !root.right && targetSum === root.val) return true; + // return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); +}; +``` + From 07e99cf9ccb7f64d53ecca898fe4f233d9fbec00 Mon Sep 17 00:00:00 2001 From: HermanZzz Date: Wed, 12 May 2021 16:01:18 +0800 Subject: [PATCH 022/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00113.=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=80=BB=E5=92=8C-ii=20=E7=9A=84JavaScript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 51ee0872..718a2f5b 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -314,6 +314,8 @@ Go: JavaScript: +0112.路径总和 + ```javascript /** * @param {TreeNode} root @@ -321,6 +323,7 @@ JavaScript: * @return {boolean} */ let hasPathSum = function (root, targetSum) { + // 递归法 const traversal = (node, cnt) => { // 遇到叶子节点,并且计数为0 if (cnt === 0 && !node.left && !node.right) return true; @@ -343,6 +346,40 @@ let hasPathSum = function (root, targetSum) { }; ``` +0113.路径总和-ii + +```javascript +let pathSum = function (root, targetSum) { + // 递归法 + // 要遍历整个树找到所有路径,所以递归函数不需要返回值, 与112不同 + const res = []; + const travelsal = (node, cnt, path) => { + // 遇到了叶子节点且找到了和为sum的路径 + if (cnt === 0 && !node.left && !node.right) { + res.push([...path]); // 不能写res.push(path), 要深拷贝 + return; + } + if (!node.left && !node.right) return; // 遇到叶子节点而没有找到合适的边,直接返回 + // 左 (空节点不遍历) + if (node.left) { + path.push(node.left.val); + travelsal(node.left, cnt - node.left.val, path); // 递归 + path.pop(); // 回溯 + } + // 右 (空节点不遍历) + if (node.right) { + path.push(node.right.val); + travelsal(node.right, cnt - node.right.val, path); // 递归 + path.pop(); // 回溯 + } + return; + }; + if (!root) return res; + travelsal(root, targetSum - root.val, [root.val]); // 把根节点放进路径 + return res; +}; +``` + From f44cade011d2c3a20470b51156987c742f3e24b0 Mon Sep 17 00:00:00 2001 From: doo0301 Date: Wed, 12 May 2021 16:08:09 +0800 Subject: [PATCH 023/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200102.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 8c34d415..be2e9dca 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -419,7 +419,8 @@ public: Java: -```Java +``` Java + class Solution { public List> resList=new ArrayList>(); From 346b0713d8821d2d7fd9000b6cb71086d8bc0f04 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 16:48:22 +0800 Subject: [PATCH 024/177] =?UTF-8?q?Update=201049.=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E4=B8=80=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84=E9=87=8D=E9=87=8F?= =?UTF-8?q?II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加1049.最后一块石头的重量 Java版本 --- .../1049.最后一块石头的重量II.md | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 6f654fac..2fdaaa6f 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -155,7 +155,27 @@ public: Java: - +```Java +class Solution { + public int lastStoneWeightII(int[] stones) { + int sum = 0; + for (int i : stones) { + sum += i; + } + int target = sum >> 1; + //初始化dp数组 + int[] dp = new int[target + 1]; + for (int i = 0; i < stones.length; i++) { + //采用倒叙 + for (int j = target; j >= stones[i]; j--) { + //两种情况,要么放,要么不放 + dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); + } + } + return sum - 2 * dp[target]; + } +} +``` Python: From a1d15df5e0b334fbc9c2a326e878c88018e37bb7 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 16:56:05 +0800 Subject: [PATCH 025/177] =?UTF-8?q?Update=201049.=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E4=B8=80=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84=E9=87=8D=E9=87=8F?= =?UTF-8?q?II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加1049.最后一块石头的重量 Java版本 --- problems/1049.最后一块石头的重量II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 2fdaaa6f..0ffd6a3e 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -166,7 +166,7 @@ class Solution { //初始化dp数组 int[] dp = new int[target + 1]; for (int i = 0; i < stones.length; i++) { - //采用倒叙 + //采用倒序 for (int j = target; j >= stones[i]; j--) { //两种情况,要么放,要么不放 dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); From 6aaba6fdf96baac08a82f59788f1545cf812e792 Mon Sep 17 00:00:00 2001 From: simonhancrew <597494370@qq.com> Date: Wed, 12 May 2021 17:53:21 +0800 Subject: [PATCH 026/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00001.=E4=B8=A4?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20Python3=20Rust=20=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 6c9d99dd..21f798a9 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -106,6 +106,18 @@ public int[] twoSum(int[] nums, int target) { Python: +```python3 +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + hashmap={} + for ind,num in enumerate(nums): + hashmap[num] = ind + for i,num in enumerate(nums): + j = hashmap.get(target - num) + if j is not None and i!=j: + return [i,j] +``` + Go: @@ -122,6 +134,28 @@ func twoSum(nums []int, target int) []int { } ``` +Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut map = HashMap::with_capacity(nums.len()); + + for i in 0..nums.len() { + if let Some(k) = map.get(&(target - nums[i])) { + if *k != i { + return vec![*k as i32, i as i32]; + } + } + map.insert(nums[i], i); + } + panic!("not found") + } +} +``` + From 9fa21a5e8fab1073c4421189f5a0703ff1b653b2 Mon Sep 17 00:00:00 2001 From: doo0301 Date: Wed, 12 May 2021 19:56:58 +0800 Subject: [PATCH 027/177] =?UTF-8?q?=E4=BC=98=E5=8C=96=200102.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?.md=20Java=E7=89=88=E6=9C=AC=EF=BC=88=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E6=96=B9=E5=BC=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 35 +++++++++++++++++------ 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index be2e9dca..0781e01d 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -419,18 +419,17 @@ public: Java: -``` Java - - +```Java class Solution { public List> resList=new ArrayList>(); public List> levelOrder(TreeNode root) { - checkFun01(root,0); - + //checkFun01(root,0); + checkFun02(root); + return resList; } - //递归方式 + //DFS--递归方式 public void checkFun01(TreeNode node,Integer deep){ if(node==null) return; deep++; @@ -442,12 +441,33 @@ class Solution { } resList.get(deep-1).add(node.val); - checkFun01(node.left,deep); checkFun01(node.right,deep); } + + //BFS--迭代方式--借助队列 + public void checkFun02(TreeNode node){ + if(node==null) return; + Queue que=new LinkedList(); + que.offer(node); + while(!que.isEmpty()){ + List itemList=new ArrayList(); + int len=que.size(); + while(len>0){ + TreeNode tmpNode=que.poll(); + itemList.add(tmpNode.val); + + if(tmpNode.left!=null) que.offer(tmpNode.left); + if(tmpNode.right!=null) que.offer(tmpNode.right); + len--; + } + + resList.add(itemList); + } + + } ``` @@ -458,7 +478,6 @@ Go: - ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) From aeed7d9452e8328a893885de179501fa05f3301c Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 20:30:32 +0800 Subject: [PATCH 028/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00344.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0344.反转字符串 Java版本 --- problems/0344.反转字符串.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index ddb9805d..02282355 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -140,7 +140,21 @@ public: Java: - +```Java +class Solution { + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + while (l < r) { + s[l] ^= s[r]; //构造 a ^ b 的结果,并放在 a 中 + s[r] ^= s[l]; //将 a ^ b 这一结果再 ^ b ,存入b中,此时 b = a, a = a ^ b + s[l] ^= s[r]; //a ^ b 的结果再 ^ a ,存入 a 中,此时 b = a, a = b 完成交换 + l++; + r--; + } + } +} +``` Python: From 45f970eb65e7934935871d03d5508e12130a8dfc Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:49:36 +0800 Subject: [PATCH 029/177] =?UTF-8?q?Update=200707.=E8=AE=BE=E8=AE=A1?= =?UTF-8?q?=E9=93=BE=E8=A1=A8.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0707.设计链表.md | 71 +++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index f98051c9..93133b55 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -157,7 +157,78 @@ private: Java: +```Java +class MyLinkedList { + //size存储链表元素的个数 + int size; + //虚拟头结点 + ListNode head; + //初始化链表 + public MyLinkedList() { + size = 0; + head = new ListNode(0); + } + + //获取第index个节点的数值 + public int get(int index) { + //如果index非法,返回-1 + if (index < 0 || index >= size) { + return -1; + } + ListNode currentNode = head; + //包含一个虚拟头节点,所以查找第 index+1 个节点 + for (int i = 0; i <= index; i++) { + currentNode = currentNode.next; + } + return currentNode.val; + } + + //在链表最前面插入一个节点 + public void addAtHead(int val) { + addAtIndex(0, val); + } + + //在链表的最后插入一个节点 + public void addAtTail(int val) { + addAtIndex(size, val); + } + + // 在第 index 个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。 + // 如果 index 等于链表的长度,则说明是新插入的节点为链表的尾结点 + // 如果 index 大于链表的长度,则返回空 + public void addAtIndex(int index, int val) { + if (index > size) { + return; + } + if (index < 0) { + index = 0; + } + size++; + //找到要插入节点的前驱 + ListNode pred = head; + for (int i = 0; i < index; i++) { + pred = pred.next; + } + ListNode toAdd = new ListNode(val); + toAdd.next = pred.next; + pred.next = toAdd; + } + + //删除第index个节点 + public void deleteAtIndex(int index) { + if (index < 0 || index >= size) { + return; + } + size--; + ListNode pred = head; + for (int i = 0; i < index; i++) { + pred = pred.next; + } + pred.next = pred.next.next; + } +} +``` Python: From a522c18365d61deac3d8bb4e7dc72f036da6073e Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:51:36 +0800 Subject: [PATCH 030/177] =?UTF-8?q?Update=200746.=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0746.使用最小花费爬楼梯.md | 21 +++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index e87f782c..b8158205 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -203,7 +203,26 @@ public: Java: - +```Java +class Solution { + public int minCostClimbingStairs(int[] cost) { + if (cost == null || cost.length == 0) { + return 0; + } + if (cost.length == 1) { + return cost[0]; + } + int[] dp = new int[cost.length]; + dp[0] = cost[0]; + dp[1] = cost[1]; + for (int i = 2; i < cost.length; i++) { + dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i]; + } + //最后一步,如果是由倒数第二步爬,则最后一步的体力花费可以不用算 + return Math.min(dp[cost.length - 1], dp[cost.length - 2]); + } +} +``` Python: From f07c41e9b96b38dd980e85e6687b147f47749963 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:54:22 +0800 Subject: [PATCH 031/177] =?UTF-8?q?Update=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0518.零钱兑换II.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index 46e52cc0..15c9d7d0 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -188,7 +188,22 @@ public: Java: - +```Java +class Solution { + public int change(int amount, int[] coins) { + //递推表达式 + int[] dp = new int[amount + 1]; + //初始化dp数组,表示金额为0时只有一种情况,也就是什么都不装 + dp[0] = 1; + for (int i = 0; i < coins.length; i++) { + for (int j = coins[i]; j <= amount; j++) { + dp[j] += dp[j - coins[i]]; + } + } + return dp[amount]; + } +} +``` Python: From 2c1d0927d2e7f88b256451bdca5f6ef04be81de6 Mon Sep 17 00:00:00 2001 From: Powerstot <77142630+Powerstot@users.noreply.github.com> Date: Wed, 12 May 2021 20:55:21 +0800 Subject: [PATCH 032/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00541.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0541.反转字符串II Java版本 --- problems/0541.反转字符串II.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 6a84006e..7ca63675 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -101,7 +101,36 @@ public: Java: +```Java +class Solution { + public String reverseStr(String s, int k) { + StringBuffer res = new StringBuffer(); + for (int i = 0; i < s.length(); i += (2 * k)) { + StringBuffer temp = new StringBuffer(); + // 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转 + if (i + k <= s.length()) { + // 反转前 k 个字符 + temp.append(s.substring(i, i + k)); + res.append(temp.reverse()); + + // 反转完前 k 个字符之后,如果紧接着还有 k 个字符,则直接加入这 k 个字符 + if (i + 2 * k <= s.length()) { + res.append(s.substring(i + k, i + 2 * k)); + // 不足 k 个字符,则直接加入剩下所有字符 + } else { + res.append(s.substring(i + k, s.length())); + } + continue; + } + // 剩余字符少于 k 个,则将剩余字符全部反转。 + temp.append(s.substring(i, s.length())); + res.append(temp.reverse()); + } + return res.toString(); + } +} +``` Python: From 242c2120bbe15ce34187aba3aa5d35ed0a05914b Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:55:32 +0800 Subject: [PATCH 033/177] =?UTF-8?q?Update=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0474.一和零.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 7970c38e..4ec5fd4d 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -161,7 +161,33 @@ public: Java: - +```Java +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + //dp[i][j]表示i个0和j个1时的最大子集 + int[][] dp = new int[m + 1][n + 1]; + int oneNum, zeroNum; + for (String str : strs) { + oneNum = 0; + zeroNum = 0; + for (char ch : str.toCharArray()) { + if (ch == '0') { + zeroNum++; + } else { + oneNum++; + } + } + //倒序遍历 + for (int i = m; i >= zeroNum; i--) { + for (int j = n; j >= oneNum; j--) { + dp[i][j] = Math.max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1); + } + } + } + return dp[m][n]; + } +} +``` Python: From fab96e6c482e14c5b576aeef48fd1046d9bf45fc Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:56:06 +0800 Subject: [PATCH 034/177] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0?= =?UTF-8?q?=E7=9B=B8=E5=8A=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0454.四数相加II.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 71dcc1ae..a2ef928b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -88,7 +88,36 @@ public: Java: - +```Java +class Solution { + public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { + Map map = new HashMap<>(); + int temp; + int res = 0; + //统计两个数组中的元素之和,同时统计出现的次数,放入map + for (int i : nums1) { + for (int j : nums2) { + temp = i + j; + if (map.containsKey(temp)) { + map.put(temp, map.get(temp) + 1); + } else { + map.put(temp, 1); + } + } + } + //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数 + for (int i : nums3) { + for (int j : nums4) { + temp = i + j; + if (map.containsKey(0 - temp)) { + res += map.get(0 - temp); + } + } + } + return res; + } +} +``` Python: From 156a82bbba2573b3e7325f14a3ef0740eeb2b692 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:56:48 +0800 Subject: [PATCH 035/177] =?UTF-8?q?Update=200416.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E7=AD=89=E5=92=8C=E5=AD=90=E9=9B=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0416.分割等和子集.md | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 257c4d7d..789a7fb5 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -185,7 +185,41 @@ public: Java: +```Java +class Solution { + public boolean canPartition(int[] nums) { + int sum = 0; + for (int i : nums) { + sum += i; + } + if ((sum & 1) == 1) { + return false; + } + int length = nums.length; + int target = sum >> 1; + //dp[j]表示前i个元素可以找到相加等于j情况 + boolean[] dp = new boolean[target + 1]; + //对于第一个元素,只有当j=nums[0]时,才恰好填充满 + if (nums[0] <= target) { + dp[nums[0]] = true; + } + for (int i = 1; i < length; i++) { + //j由右往左直到nums[i] + for (int j = target; j >= nums[i]; j--) { + //只有两种情况,要么放,要么不放 + //取其中的TRUE值 + dp[j] = dp[j] || dp[j - nums[i]]; + } + //一旦满足,结束,因为只需要找到一组值即可 + if (dp[target]) { + return dp[target]; + } + } + return dp[target]; + } +} +``` Python: From fdb9785e443ac24c2a884bf844e5baac4b2dbb60 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:57:14 +0800 Subject: [PATCH 036/177] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91?= =?UTF-8?q?=E4=BF=A1.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index ca9b6061..742bfdc3 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -111,7 +111,31 @@ public: Java: +```Java +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + //记录杂志字符串出现的次数 + int[] arr = new int[26]; + int temp; + for (int i = 0; i < magazine.length(); i++) { + temp = magazine.charAt(i) - 'a'; + arr[temp]++; + } + for (int i = 0; i < ransomNote.length(); i++) { + temp = ransomNote.charAt(i) - 'a'; + //对于金信中的每一个字符都在数组中查找 + //找到相应位减一,否则找不到返回false + if (arr[temp] > 0) { + arr[temp]--; + } else { + return false; + } + } + return true; + } +} +``` Python: From 6c40ec595ad8fcf2e10a50279dbc331dc289d327 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:57:43 +0800 Subject: [PATCH 037/177] =?UTF-8?q?Update=200377.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=E2=85=A3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0377.组合总和Ⅳ.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index b0b83718..8f8cfd86 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -147,7 +147,23 @@ C++测试用例有超过两个树相加超过int的数据,所以需要在if里 Java: +```Java +class Solution { + public int combinationSum4(int[] nums, int target) { + int[] dp = new int[target + 1]; + dp[0] = 1; + for (int i = 0; i <= target; i++) { + for (int j = 0; j < nums.length; j++) { + if (i >= nums[j]) { + dp[i] += dp[i - nums[j]]; + } + } + } + return dp[target]; + } +} +``` Python: From d5c333f1bab065b663788cc2939cbd8484d7850b Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:58:17 +0800 Subject: [PATCH 038/177] =?UTF-8?q?Update=200322.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0322.零钱兑换.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index fbb9c6df..e67695d8 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -181,7 +181,31 @@ public: Java: - +```Java +class Solution { + public int coinChange(int[] coins, int amount) { + int max = Integer.MAX_VALUE; + int[] dp = new int[amount + 1]; + //初始化dp数组为最大值 + for (int j = 0; j < dp.length; j++) { + dp[j] = max; + } + //当金额为0时需要的硬币数目为0 + dp[0] = 0; + for (int i = 0; i < coins.length; i++) { + //正序遍历:完全背包每个硬币可以选择多次 + for (int j = coins[i]; j <= amount; j++) { + //只有dp[j-coins[i]]不是初始最大值时,该位才有选择的必要 + if (dp[j - coins[i]] != max) { + //选择硬币数目最小的情况 + dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1); + } + } + } + return dp[amount] == max ? -1 : dp[amount]; + } +} +``` Python: From b09bf150dab7b9161c956eeb94f17bd72eb759ad Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:58:47 +0800 Subject: [PATCH 039/177] =?UTF-8?q?Update=200055.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0055.跳跃游戏.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 0cad1fa7..179ac246 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -86,7 +86,25 @@ public: Java: - +```Java +class Solution { + public boolean canJump(int[] nums) { + if (nums.length == 1) { + return true; + } + //覆盖范围 + int coverRange = nums[0]; + //在覆盖范围内更新最大的覆盖范围 + for (int i = 0; i <= coverRange; i++) { + coverRange = Math.max(coverRange, i + nums[i]); + if (coverRange >= nums.length - 1) { + return true; + } + } + return false; + } +} +``` Python: From 2e15cc33308112a43356db56a26a5c2d54049f6b Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:59:19 +0800 Subject: [PATCH 040/177] =?UTF-8?q?Update=200045.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8FII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 2def83a9..b8e369e6 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -143,7 +143,36 @@ public: Java: - +```Java +class Solution { + public int jump(int[] nums) { + if (nums == null || nums.length == 0 || nums.length == 1) { + return 0; + } + //记录跳跃的次数 + int count=0; + //当前的覆盖最大区域 + int curDistance = 0; + //最大的覆盖区域 + int maxDistance = 0; + for (int i = 0; i < nums.length; i++) { + //在可覆盖区域内更新最大的覆盖区域 + maxDistance = Math.max(maxDistance,i+nums[i]); + //说明当前一步,再跳一步就到达了末尾 + if (maxDistance>=nums.length-1){ + count++; + break; + } + //走到当前覆盖的最大区域时,更新下一步可达的最大区域 + if (i==curDistance){ + curDistance = maxDistance; + count++; + } + } + return count; + } +} +``` Python: From f9505965999d971725136bd7e4f56cfc94cb5ab9 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 20:59:49 +0800 Subject: [PATCH 041/177] =?UTF-8?q?Update=200040.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8CII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index ffcbe212..50898016 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -255,7 +255,43 @@ public: Java: +```Java +class Solution { + List> lists = new ArrayList<>(); + Deque deque = new LinkedList<>(); + int sum = 0; + public List> combinationSum2(int[] candidates, int target) { + //为了将重复的数字都放到一起,所以先进行排序 + Arrays.sort(candidates); + //加标志数组,用来辅助判断同层节点是否已经遍历 + boolean[] flag = new boolean[candidates.length]; + backTracking(candidates, target, 0, flag); + return lists; + } + + public void backTracking(int[] arr, int target, int index, boolean[] flag) { + if (sum == target) { + lists.add(new ArrayList(deque)); + return; + } + for (int i = index; i < arr.length && arr[i] + sum <= target; i++) { + //出现重复节点,同层的第一个节点已经被访问过,所以直接跳过 + if (i > 0 && arr[i] == arr[i - 1] && !flag[i - 1]) { + continue; + } + flag[i] = true; + sum += arr[i]; + deque.push(arr[i]); + //每个节点仅能选择一次,所以从下一位开始 + backTracking(arr, target, i + 1, flag); + int temp = deque.pop(); + flag[i] = false; + sum -= temp; + } + } +} +``` Python: From 988211e8892fdba5c9c2b15a0489bd7734af946e Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 21:00:14 +0800 Subject: [PATCH 042/177] =?UTF-8?q?Update=200039.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index f983a994..ab118ee0 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -236,7 +236,39 @@ public: Java: +```Java +class Solution { + List> lists = new ArrayList<>(); + Deque deque = new LinkedList<>(); + public List> combinationSum3(int k, int n) { + int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; + backTracking(arr, n, k, 0); + return lists; + } + + public void backTracking(int[] arr, int n, int k, int startIndex) { + //如果 n 小于0,没必要继续本次递归,已经不符合要求了 + if (n < 0) { + return; + } + if (deque.size() == k) { + if (n == 0) { + lists.add(new ArrayList(deque)); + } + return; + } + for (int i = startIndex; i < arr.length - (k - deque.size()) + 1; i++) { + deque.push(arr[i]); + //减去当前元素 + n -= arr[i]; + backTracking(arr, n, k, i + 1); + //恢复n + n += deque.pop(); + } + } +} +``` Python: From 8fbfc3af8c65aa7e2061bb89c028dc77f0c05f3a Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Wed, 12 May 2021 21:01:01 +0800 Subject: [PATCH 043/177] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index afc1f144..ec1335c6 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -208,8 +208,21 @@ Java: Python: -Go: +```Go +func invertTree(root *TreeNode) *TreeNode { + if root ==nil{ + return nil + } + temp:=root.Left + root.Left=root.Right + root.Right=temp + + invertTree(root.Left) + invertTree(root.Right) + return root +} +``` From d5b378e1421c93d64f86c9752dd34ba39e7bf37c Mon Sep 17 00:00:00 2001 From: LehiChiang <1471277588@qq.com> Date: Wed, 12 May 2021 21:01:25 +0800 Subject: [PATCH 044/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00111.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20Python=E7=89=88=E6=9C=AC=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 46 ++++++++++++++++++++++- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 430cd5d6..6c6b4632 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -195,9 +195,51 @@ public: Java: - Python: +递归法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left and not root.right: + return 1 + + min_depth = 10**9 + if root.left: + min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 + if root.right: + min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 + return min_depth + 1 +``` + +迭代法: + +```python +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + que = deque() + que.append(root) + res = 1 + + while que: + for _ in range(len(que)): + node = que.popleft() + # 当左右孩子都为空的时候,说明是最低点的一层了,退出 + if not node.left and not node.right: + return res + if node.left is not None: + que.append(node.left) + if node.right is not None: + que.append(node.right) + res += 1 + return res +``` + Go: @@ -208,4 +250,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 From ea2c08f0cbf58f997f7e236039126e9869f95e6a Mon Sep 17 00:00:00 2001 From: weikunkun Date: Wed, 12 May 2021 21:07:20 +0800 Subject: [PATCH 045/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00203.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 58 ++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index e6667091..9fca1ee0 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -138,7 +138,63 @@ public: Java: - +```java +/** + * 添加虚节点方式 + * 时间复杂度 O(n) + * 空间复杂度 O(1) + * @param head + * @param val + * @return + */ +public ListNode removeElements(ListNode head, int val) { + if (head == null) { + return head; + } + // 因为删除可能涉及到头节点,所以设置dummy节点,统一操作 + ListNode dummy = new ListNode(-1, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null) { + if (cur.val == val) { + pre.next = cur.next; + } else { + pre = cur; + } + cur = cur.next; + } + return dummy.next; +} +/** + * 不添加虚拟节点方式 + * 时间复杂度 O(n) + * 空间复杂度 O(1) + * @param head + * @param val + * @return + */ +public ListNode removeElements(ListNode head, int val) { + while (head != null && head.val == val) { + head = head.next; + } + // 已经为null,提前退出 + if (head == null) { + return head; + } + // 已确定当前head.val != val + ListNode pre = head; + ListNode cur = head.next; + while (cur != null) { + if (cur.val == val) { + pre.next = cur.next; + } else { + pre = cur; + } + cur = cur.next; + } + return head; +} +``` Python: From 9fbdb32bcfe8f921d872ad4826076f2bd2bd8ad6 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Wed, 12 May 2021 21:14:26 +0800 Subject: [PATCH 046/177] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E4=B8=93=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 +- .../0024.两两交换链表中的节点.md | 100 ++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) create mode 100644 problems/0024.两两交换链表中的节点.md diff --git a/README.md b/README.md index df397457..276c8313 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,11 @@ 1. [关于链表,你该了解这些!](./problems/链表理论基础.md) 2. [链表:听说用虚拟头节点会方便很多?](./problems/0203.移除链表元素.md) 3. [链表:一道题目考察了常见的五个操作!](./problems/0707.设计链表.md) -4. [链表:听说过两天反转链表又写不出来了?](./problems/0206.翻转链表.md) -5. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) -5. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) -6. [链表:总结篇!](./problems/链表总结篇.md) +4. [链表:听说过两天反转链表又写不出来了?](./problems/0206.翻转链表.md) +5. [链表:两两交换链表中的节点](./problems/0024.两两交换链表中的节点.md) +6. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) +7. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) +8. [链表:总结篇!](./problems/链表总结篇.md) ## 哈希表 diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md new file mode 100644 index 00000000..aa284279 --- /dev/null +++ b/problems/0024.两两交换链表中的节点.md @@ -0,0 +1,100 @@ + +

+ + + + +

+

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ +## 24. 两两交换链表中的节点 + +给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 + +你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 + + +![24.两两交换链表中的节点-题意](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9-%E9%A2%98%E6%84%8F.jpg) + +## 思路 + +这道题目正常模拟就可以了。 + +建议使用虚拟头结点,这样会方便很多,要不然每次针对头结点(没有前一个指针指向头结点),还要单独处理。 + +对虚拟头结点的操作,还不熟悉的话,可以看这篇[链表:听说用虚拟头节点会方便很多?](https://mp.weixin.qq.com/s/L5aanfALdLEwVWGvyXPDqA)。 + +接下来就是交换相邻两个元素了,**此时一定要画图,不画图,操作多个指针很容易乱,而且要操作的先后顺序** + +初始时,cur指向虚拟头结点,然后进行如下三步: + +![24.两两交换链表中的节点1](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B91.png) + +操作之后,链表如下: + +![24.两两交换链表中的节点2](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B92.png) + +看这个可能就更直观一些了: + + +![24.两两交换链表中的节点3](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B93.png) + +对应的C++代码实现如下: (注释中详细和如上图中的三步做对应) + +```C++ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点 + dummyHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作 + ListNode* cur = dummyHead; + while(cur->next != nullptr && cur->next->next != nullptr) { + ListNode* tmp = cur->next; // 记录临时节点 + ListNode* tmp1 = cur->next->next->next; // 记录临时节点 + + cur->next = cur->next->next; // 步骤一 + cur->next->next = tmp; // 步骤二 + cur->next->next->next = tmp1; // 步骤三 + + cur = cur->next->next; // cur移动两位,准备下一轮交换 + } + return dummyHead->next; + } +}; +``` +* 时间复杂度:$O(n)$ +* 空间复杂度:$O(1)$ + +## 拓展 + +**这里还是说一下,大家不必太在意力扣上执行用时,打败多少多少用户,这个统计不准确的。** + +做题的时候自己能分析出来时间复杂度就可以了,至于力扣上执行用时,大概看一下就行。 + +上面的代码我第一次提交执行用时8ms,打败6.5%的用户,差点吓到我了。 + +心想应该没有更好的方法了吧,也就O(n)的时间复杂度,重复提交几次,这样了: + +![24.两两交换链表中的节点](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.png) + +力扣上的统计如果两份代码是 100ms 和 300ms的耗时,其实是需要注意的。 + +如果一个是 4ms 一个是 12ms,看上去好像是一个打败了80%,一个打败了20%,其实是没有差别的。 只不过是力扣上统计的误差而已。 + + +## 其他语言版本 + + +Java: + + +Python: + +Go: + + +----------------------- +* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) +* B站视频:[代码随想录](https://space.bilibili.com/525438321) +* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +
From 2f2e25de61fb1eaef44485239d40129bab753c91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:25:52 +0900 Subject: [PATCH 047/177] =?UTF-8?q?Update=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新Java版本 --- problems/0046.全排列.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 5f7b1ac0..05d86785 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -147,7 +147,41 @@ public: Java: +```java +class Solution { + List> result = new ArrayList<>();// 存放符合条件结果的集合 + LinkedList path = new LinkedList<>();// 用来存放符合条件结果 + boolean[] used; + public List> permute(int[] nums) { + if (nums.length == 0){ + return result; + } + used = new boolean[nums.length]; + permuteHelper(nums); + return result; + } + private void permuteHelper(int[] nums){ + if (path.size() == nums.length){ + result.add(new ArrayList<>(path)); + return; + } + for (int i = 0; i < nums.length; i++){ + // if (path.contains(nums[i])){ + // continue; + // } + if (used[i]){ + continue; + } + used[i] = true; + path.add(nums[i]); + permuteHelper(nums); + path.removeLast(); + used[i] = false; + } + } +} +``` Python: From 7fa6fa8823397bee24d3d66a0cb59719404a6efc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:32:06 +0900 Subject: [PATCH 048/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200037.=E8=A7=A3?= =?UTF-8?q?=E6=95=B0=E7=8B=AC.md=20Java=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0037.解数独.md | 65 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 75e2d3cd..7b59fad9 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -219,7 +219,72 @@ public: Java: +```java +class Solution { + public void solveSudoku(char[][] board) { + solveSudokuHelper(board); + } + private boolean solveSudokuHelper(char[][] board){ + //「一个for循环遍历棋盘的行,一个for循环遍历棋盘的列, + // 一行一列确定下来之后,递归遍历这个位置放9个数字的可能性!」 + for (int i = 0; i < 9; i++){ // 遍历行 + for (int j = 0; j < 9; j++){ // 遍历列 + if (board[i][j] != '.'){ // 跳过原始数字 + continue; + } + for (char k = '1'; k <= '9'; k++){ // (i, j) 这个位置放k是否合适 + if (isValidSudoku(i, j, k, board)){ + board[i][j] = k; + if (solveSudokuHelper(board)){ // 如果找到合适一组立刻返回 + return true; + } + board[i][j] = '.'; + } + } + // 9个数都试完了,都不行,那么就返回false + return false; + // 因为如果一行一列确定下来了,这里尝试了9个数都不行,说明这个棋盘找不到解决数独问题的解! + // 那么会直接返回, 「这也就是为什么没有终止条件也不会永远填不满棋盘而无限递归下去!」 + } + } + // 遍历完没有返回false,说明找到了合适棋盘位置了 + return true; + } + + /** + * 判断棋盘是否合法有如下三个维度: + * 同行是否重复 + * 同列是否重复 + * 9宫格里是否重复 + */ + private boolean isValidSudoku(int row, int col, char val, char[][] board){ + // 同行是否重复 + for (int i = 0; i < 9; i++){ + if (board[row][i] == val){ + return false; + } + } + // 同列是否重复 + for (int j = 0; j < 9; j++){ + if (board[j][col] == val){ + return false; + } + } + // 9宫格里是否重复 + int startRow = (row / 3) * 3; + int startCol = (col / 3) * 3; + for (int i = startRow; i < startRow + 3; i++){ + for (int j = startCol; j < startCol + 3; j++){ + if (board[i][j] == val){ + return false; + } + } + } + return true; + } +} +``` Python: From a77901400534ad01cddfca27ba6d2aa1e3cc791a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:34:43 +0900 Subject: [PATCH 049/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200053.=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E5=AD=90=E5=BA=8F=E5=92=8C.md=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8a9d748..b8b11a57 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -139,7 +139,25 @@ public: Java: - +```java +class Solution { + public int maxSubArray(int[] nums) { + if (nums.length == 1){ + return nums[0]; + } + int sum = Integer.MIN_VALUE; + int count = 0; + for (int i = 0; i < nums.length; i++){ + count += nums[i]; + sum = Math.max(sum, count); // 取区间累计的最大值(相当于不断确定最大子序终止位置) + if (count <= 0){ + count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和 + } + } + return sum; + } +} +``` Python: From d9d1f669ba9a7eb7a8c17c9136a000e9673c7f5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:37:31 +0900 Subject: [PATCH 050/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200077.=E7=BB=84?= =?UTF-8?q?=E5=90=88.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 3dfb5216..f31766e0 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -340,6 +340,33 @@ public: Java: +```java +class Solution { + List> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> combine(int n, int k) { + combineHelper(n, k, 1); + return result; + } + + /** + * 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex + * @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。 + */ + private void combineHelper(int n, int k, int startIndex){ + //终止条件 + if (path.size() == k){ + result.add(new ArrayList<>(path)); + return; + } + for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){ + path.add(i); + combineHelper(n, k, i + 1); + path.removeLast(); + } + } +} +``` Python: From c46f5d6f8f012518fc465e924ea1b636c088672d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:39:37 +0900 Subject: [PATCH 051/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200077.=E7=BB=84?= =?UTF-8?q?=E5=90=88=E4=BC=98=E5=8C=96.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合优化.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 2af123d1..a8a17858 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -147,7 +147,33 @@ public: Java: +``` +class Solution { + List> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> combine(int n, int k) { + combineHelper(n, k, 1); + return result; + } + /** + * 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex + * @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。 + */ + private void combineHelper(int n, int k, int startIndex){ + //终止条件 + if (path.size() == k){ + result.add(new ArrayList<>(path)); + return; + } + for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){ + path.add(i); + combineHelper(n, k, i + 1); + path.removeLast(); + } + } +} +``` Python: From 06d8ddee515cb3ce994a37ec416adde34979b236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:42:29 +0900 Subject: [PATCH 052/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200078.=E5=AD=90?= =?UTF-8?q?=E9=9B=86.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 8c68843d..77854133 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -177,7 +177,33 @@ public: Java: +```java +class Solution { + List> result = new ArrayList<>();// 存放符合条件结果的集合 + LinkedList path = new LinkedList<>();// 用来存放符合条件结果 + public List> subsets(int[] nums) { + if (nums.length == 0){ + result.add(new ArrayList<>()); + return result; + } + Arrays.sort(nums); + subsetsHelper(nums, 0); + return result; + } + private void subsetsHelper(int[] nums, int startIndex){ + result.add(new ArrayList<>(path));//「遍历这个树的时候,把所有节点都记录下来,就是要求的子集集合」。 + if (startIndex >= nums.length){ //终止条件可不加 + return; + } + for (int i = startIndex; i < nums.length; i++){ + path.add(nums[i]); + subsetsHelper(nums, i + 1); + path.removeLast(); + } + } +} +``` Python: From e8f8e7b8034d0cb27af5634b3bbe207e8d7ee6bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:44:41 +0900 Subject: [PATCH 053/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200090.=E5=AD=90?= =?UTF-8?q?=E9=9B=86II.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index cc5fd571..47db79f7 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -172,7 +172,40 @@ if (i > startIndex && nums[i] == nums[i - 1] ) { Java: - +```java +class Solution { + List> result = new ArrayList<>();// 存放符合条件结果的集合 + LinkedList path = new LinkedList<>();// 用来存放符合条件结果 + boolean[] used; + public List> subsetsWithDup(int[] nums) { + if (nums.length == 0){ + result.add(path); + return result; + } + Arrays.sort(nums); + used = new boolean[nums.length]; + subsetsWithDupHelper(nums, 0); + return result; + } + + private void subsetsWithDupHelper(int[] nums, int startIndex){ + result.add(new ArrayList<>(path)); + if (startIndex >= nums.length){ + return; + } + for (int i = startIndex; i < nums.length; i++){ + if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]){ + continue; + } + path.add(nums[i]); + used[i] = true; + subsetsWithDupHelper(nums, i + 1); + path.removeLast(); + used[i] = false; + } + } +} +``` Python: From a3ba386ad6037ffafb80e2dac466b0b37146e304 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 21:59:18 +0800 Subject: [PATCH 054/177] =?UTF-8?q?Update=200017.=E7=94=B5=E8=AF=9D?= =?UTF-8?q?=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 6f51a181..76d5655d 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -240,7 +240,45 @@ public: Java: +```Java +class Solution { + //设置全局列表存储最后的结果 + List list = new ArrayList<>(); + + public List letterCombinations(String digits) { + if (digits == null || digits.length() == 0) { + return list; + } + //初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串"" + String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + //迭代处理 + backTracking(digits, numString, 0); + return list; + + } + + //每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild + StringBuilder temp = new StringBuilder(); + + //比如digits如果为"23",num 为0,则str表示2对应的 abc + public void backTracking(String digits, String[] numString, int num) { + //遍历全部一次记录一次得到的字符串 + if (num == digits.length()) { + list.add(temp.toString()); + return; + } + //str 表示当前num对应的字符串 + String str = numString[digits.charAt(num) - '0']; + for (int i = 0; i < str.length(); i++) { + temp.append(str.charAt(i)); + backTracking(digits, numString, num + 1); + //剔除末尾的继续尝试 + temp.deleteCharAt(temp.length() - 1); + } + } +} +``` Python: From 5a799c674ee78df7c25247c29ef3667592d7980b Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 22:20:54 +0800 Subject: [PATCH 055/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200017.=E7=94=B5?= =?UTF-8?q?=E8=AF=9D=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84?= =?UTF-8?q?=E5=90=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 76d5655d..5e856df4 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -242,7 +242,6 @@ public: Java: ```Java class Solution { - //设置全局列表存储最后的结果 List list = new ArrayList<>(); From c2fd043de06e9151863e1f9ceffcddae0f180d11 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Wed, 12 May 2021 22:23:51 +0800 Subject: [PATCH 056/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200017.=E7=94=B5?= =?UTF-8?q?=E8=AF=9D=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84?= =?UTF-8?q?=E5=90=88.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 5e856df4..f06ed80a 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -242,6 +242,7 @@ public: Java: ```Java class Solution { + //设置全局列表存储最后的结果 List list = new ArrayList<>(); @@ -271,6 +272,7 @@ class Solution { String str = numString[digits.charAt(num) - '0']; for (int i = 0; i < str.length(); i++) { temp.append(str.charAt(i)); + //回溯 backTracking(digits, numString, num + 1); //剔除末尾的继续尝试 temp.deleteCharAt(temp.length() - 1); From 49eed9c8a3d4f862c5ff75c08c31c0fe54bf2fbf Mon Sep 17 00:00:00 2001 From: LehiChiang <1471277588@qq.com> Date: Wed, 12 May 2021 22:56:39 +0800 Subject: [PATCH 057/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00225.=E7=94=A8?= =?UTF-8?q?=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88/0232.=E7=94=A8?= =?UTF-8?q?=E6=A0=88=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 53 +++++++++++++++++++++++++- problems/0232.用栈实现队列.md | 59 +++++++++++++++++++++++++++-- 2 files changed, 107 insertions(+), 5 deletions(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 49b5c62b..4018364a 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -154,9 +154,58 @@ public: ## 其他语言版本 - Java: +```java +class MyStack { + + Queue queue1; // 和栈中保持一样元素的队列 + Queue queue2; // 辅助队列 + + /** Initialize your data structure here. */ + public MyStack() { + queue1 = new LinkedList<>(); + queue2 = new LinkedList<>(); + } + + /** Push element x onto stack. */ + public void push(int x) { + queue2.offer(x); // 先放在辅助队列中 + while (!queue1.isEmpty()){ + queue2.offer(queue1.poll()); + } + Queue queueTemp; + queueTemp = queue1; + queue1 = queue2; + queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中 + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可 + } + + /** Get the top element. */ + public int top() { + return queue1.peek(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return queue1.isEmpty(); + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + Python: @@ -227,4 +276,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/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 9907b476..abdc363d 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -19,7 +19,7 @@ push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 -  + 示例: @@ -129,9 +129,62 @@ public: ## 其他语言版本 - Java: +```java +class MyQueue { + + Stack stack1; + Stack stack2; + + /** Initialize your data structure here. */ + public MyQueue() { + stack1 = new Stack<>(); // 负责进栈 + stack2 = new Stack<>(); // 负责出栈 + } + + /** Push element x to the back of queue. */ + public void push(int x) { + stack1.push(x); + } + + /** Removes the element from in front of queue and returns that element. */ + public int pop() { + dumpStack1(); + return stack2.pop(); + } + + /** Get the front element. */ + public int peek() { + dumpStack1(); + return stack2.peek(); + } + + /** Returns whether the queue is empty. */ + public boolean empty() { + return stack1.isEmpty() && stack2.isEmpty(); + } + + // 如果stack2为空,那么将stack1中的元素全部放到stack2中 + private void dumpStack1(){ + if (stack2.isEmpty()){ + while (!stack1.isEmpty()){ + stack2.push(stack1.pop()); + } + } + } +} + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * boolean param_4 = obj.empty(); + */ +``` + Python: @@ -145,4 +198,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 From 9d00f80c18411d297e98bac370458d0cd573e8d3 Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Wed, 12 May 2021 23:19:18 +0800 Subject: [PATCH 058/177] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0053.最大子序和.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8a9d748..05c08a66 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -142,7 +142,19 @@ Java: Python: - +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + result = -float('inf') + count = 0 + for i in range(len(nums)): + count += nums[i] + if count > result: + result = count + if count <= 0: + count = 0 + return result +``` Go: From cce2cffb7314cf863088579ba2b90dfdc0cfb981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E5=85=88=E5=AF=8C?= Date: Thu, 13 May 2021 07:48:32 +0800 Subject: [PATCH 059/177] =?UTF-8?q?0078.=E5=AD=90=E9=9B=86.md=20Javascript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 8c68843d..5054246f 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -184,7 +184,24 @@ Python: Go: +Javascript: +```Javascript +var subsets = function(nums) { + let result = [] + let path = [] + function backtracking(startIndex) { + result.push(path.slice()) + for(let i = startIndex; i < nums.length; i++) { + path.push(nums[i]) + backtracking(i + 1) + path.pop() + } + } + backtracking(0) + return result +}; +``` ----------------------- From 2132ce0e1634f65c585df3b112d8dca3a67ce0d3 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 09:03:10 +0800 Subject: [PATCH 060/177] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN?= =?UTF-8?q?=E4=B8=AA=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0019.删除链表的倒数第N个节点.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 3b6dde1e..3b89dabd 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -112,7 +112,28 @@ class Solution { } } ``` +Go: +```Go +func removeNthFromEnd(head *ListNode, n int) *ListNode { + result:=&ListNode{} + result.Next=head + var pre *ListNode + cur:=result + i:=1 + for head!=nil{ + if i>=n{ + pre=cur + cur=cur.Next + } + head=head.Next + i++ + } + pre.Next=pre.Next.Next + return result.Next + +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From cf42d80efc34e549f73c91dd22f2fbdbcbd39778 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 09:24:19 +0800 Subject: [PATCH 061/177] =?UTF-8?q?Update=200015.=E4=B8=89=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 55e22887..96dc1ac3 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -221,6 +221,40 @@ Python: Go: +```Go +func threeSum(nums []int)[][]int{ + sort.Ints(nums) + res:=[][]int{} + + for i:=0;i0{ + break + } + if i>0&&n1==nums[i-1]{ + continue + } + l,r:=i+1,len(nums)-1 + for l Date: Thu, 13 May 2021 09:32:54 +0800 Subject: [PATCH 062/177] =?UTF-8?q?Update=200198.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8D.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0198.打家劫舍.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index b9ccec45..c64648ad 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -117,6 +117,33 @@ Python: Go: +```Go +func rob(nums []int) int { + if len(nums)<1{ + return 0 + } + if len(nums)==1{ + return nums[0] + } + if len(nums)==2{ + return max(nums[0],nums[1]) + } + dp :=make([]int,len(nums)) + dp[0]=nums[0] + dp[1]=max(nums[0],nums[1]) + for i:=2;ib{ + return a + } + return b +} +``` From 2e2f7735d6b99bb73f0b96f11c205fe70fa774a2 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:37:33 +0800 Subject: [PATCH 063/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=89=91=E6=8C=87Off?= =?UTF-8?q?er05.=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 7881adf3..5f89241b 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -129,7 +129,26 @@ for (int i = 0; i < a.size(); i++) { Java: - +```Java +//使用一个新的对象,复制 str,复制的过程对其判断,是空格则替换,否则直接复制,类似于数组复制 +public static String replaceSpace(StringBuffer str) { + if (str == null) { + return null; + } + //选用 StringBuilder 单线程使用,比较快,选不选都行 + StringBuilder sb = new StringBuilder(); + //使用 sb 逐个复制 str ,碰到空格则替换,否则直接复制 + for (int i = 0; i < str.length(); i++) { + //str.charAt(i) 为 char 类型,为了比较需要将其转为和 " " 相同的字符串类型 + if (" ".equals(String.valueOf(str.charAt(i)))){ + sb.append("%20"); + } else { + sb.append(str.charAt(i)); + } + } + return sb.toString(); + } +``` Python: From 234eb01010164efde87c7755858b9035b6ae1dce Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Thu, 13 May 2021 09:37:53 +0800 Subject: [PATCH 064/177] Update --- problems/0024.两两交换链表中的节点.md | 2 +- problems/0541.反转字符串II.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index aa284279..9f07b4f7 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -14,7 +14,7 @@ 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 -![24.两两交换链表中的节点-题意](https://code-thinking.cdn.bcebos.com/pics/24.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9-%E9%A2%98%E6%84%8F.jpg) +24.两两交换链表中的节点-题意 ## 思路 diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 6a84006e..893c92f9 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -46,7 +46,7 @@ https://leetcode-cn.com/problems/reverse-string-ii/ 使用C++库函数reverse的版本如下: -``` +```C++ class Solution { public: string reverseStr(string s, int k) { @@ -68,7 +68,8 @@ public: 那么我们也可以实现自己的reverse函数,其实和题目[344. 反转字符串](https://mp.weixin.qq.com/s/X02S61WCYiCEhaik6VUpFA)道理是一样的。 下面我实现的reverse函数区间是左闭右闭区间,代码如下: -``` + +```C++ class Solution { public: void reverse(string& s, int start, int end) { From 10f35bd6269c6a3b9096972a93bfe63d7e5e4094 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 09:39:02 +0800 Subject: [PATCH 065/177] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8a9d748..e6d3f1c8 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -145,8 +145,29 @@ Python: Go: +```Go +func maxSubArray(nums []int) int { + if len(nums)<1{ + return 0 + } + dp:=make([]int,len(nums)) + result:=nums[0] + dp[0]=nums[0] + for i:=1;ib{ + return a + }else{ + return b + } +} +``` ----------------------- From 4a582a32fbc984e0bde728ba7e787430af437f9d Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:40:40 +0800 Subject: [PATCH 066/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A01047.=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E6=89=80?= =?UTF-8?q?=E6=9C=89=E7=9B=B8=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9=20Java?= =?UTF-8?q?=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...除字符串中的所有相邻重复项.md | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 7a06f02d..d5a8c4ed 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -122,7 +122,28 @@ public: Java: - +```Java +class Solution { + public String removeDuplicates(String S) { + Deque deque = new LinkedList<>(); + char ch; + for (int i = 0; i < S.length(); i++) { + ch = S.charAt(i); + if (deque.isEmpty() || deque.peek() != ch) { + deque.push(ch); + } else { + deque.pop(); + } + } + String str = ""; + //剩余的元素即为不重复的元素 + while (!deque.isEmpty()) { + str = deque.pop() + str; + } + return str; + } +} +``` Python: From a14aafbaec8b0ad94d1b9fe7e994491c7f4e747b Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 09:43:05 +0800 Subject: [PATCH 067/177] =?UTF-8?q?Update=200070.=E7=88=AC=E6=A5=BC?= =?UTF-8?q?=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 6ae6adc7..f0a08f99 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -230,7 +230,20 @@ class Solution: ``` Go: - +```Go +func climbStairs(n int) int { + if n==1{ + return 1 + } + dp:=make([]int,n+1) + dp[1]=1 + dp[2]=2 + for i:=3;i<=n;i++{ + dp[i]=dp[i-1]+dp[i-2] + } + return dp[n] +} +``` From ebbeb35b1164003fb9367d90c7647e2e567f5ff8 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:43:25 +0800 Subject: [PATCH 068/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00239.=E6=BB=91?= =?UTF-8?q?=E5=8A=A8=E7=AA=97=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC=20Java?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 709fa09e..781bfa6f 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -207,7 +207,60 @@ public: Java: +```Java +//自定义数组 +class MyQueue { + Deque deque = new LinkedList<>(); + //弹出元素时,比较当前要弹出的数值是否等于队列出口的数值,如果相等则弹出 + //同时判断队列当前是否为空 + void poll(int val) { + if (!deque.isEmpty() && val == deque.peek()) { + deque.poll(); + } + } + //添加元素时,如果要添加的元素大于入口处的元素,就将入口元素弹出 + //保证队列元素单调递减 + //比如此时队列元素3,1,2将要入队,比1大,所以1弹出,此时队列:3,2 + void add(int val) { + while (!deque.isEmpty() && val > deque.getLast()) { + deque.removeLast(); + } + deque.add(val); + } + //队列队顶元素始终为最大值 + int peek() { + return deque.peek(); + } +} +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + if (nums.length == 1) { + return nums; + } + int len = nums.length - k + 1; + //存放结果元素的数组 + int[] res = new int[len]; + int num = 0; + //自定义队列 + MyQueue myQueue = new MyQueue(); + //先将前k的元素放入队列 + for (int i = 0; i < k; i++) { + myQueue.add(nums[i]); + } + res[num++] = myQueue.peek(); + for (int i = k; i < nums.length; i++) { + //滑动窗口移除最前面的元素,移除是判断该元素是否放入队列 + myQueue.poll(nums[i - k]); + //滑动窗口加入最后面的元素 + myQueue.add(nums[i]); + //记录对应的最大值 + res[num++] = myQueue.peek(); + } + return res; + } +} +``` Python: From d646ad263d9bf421559479b3d73458b586dca691 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:45:18 +0800 Subject: [PATCH 069/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00376.=E6=91=86?= =?UTF-8?q?=E5=8A=A8=E5=BA=8F=E5=88=97=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 6ae76526..fa90142d 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -111,7 +111,31 @@ public: Java: - +```Java +class Solution { + public int wiggleMaxLength(int[] nums) { + if (nums == null || nums.length <= 1) { + return nums.length; + } + //当前差值 + int curDiff = 0; + //上一个差值 + int preDiff = 0; + int count = 1; + for (int i = 1; i < nums.length; i++) { + //得到当前差值 + curDiff = nums[i] - nums[i - 1]; + //如果当前差值和上一个差值为一正一负 + //等于0的情况表示初始时的preDiff + if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) { + count++; + preDiff = curDiff; + } + } + return count; + } +} +``` Python: From 538aaf527ed61cedf6ee09466e2bb81fe6177f99 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:46:24 +0800 Subject: [PATCH 070/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00279.=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E5=B9=B3=E6=96=B9=E6=95=B0=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0279.完全平方数.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index 39260926..d72e9099 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -159,7 +159,28 @@ public: Java: - +```Java +class Solution { + public int numSquares(int n) { + int max = Integer.MAX_VALUE; + int[] dp = new int[n + 1]; + //初始化 + for (int j = 0; j <= n; j++) { + dp[j] = max; + } + //当和为0时,组合的个数为0 + dp[0] = 0; + for (int i = 1; i * i <= n; i++) { + for (int j = i * i; j <= n; j++) { + if (dp[j - i * i] != max) { + dp[j] = Math.min(dp[j], dp[j - i * i] + 1); + } + } + } + return dp[n]; + } +} +``` Python: From 9bae5a96c092f8dd30f326f9cfa5ded5408f7e69 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:47:49 +0800 Subject: [PATCH 071/177] =?UTF-8?q?Update=200096.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0096.不同的二叉搜索树 Java版本 --- problems/0096.不同的二叉搜索树.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index 2764277c..98c993e4 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -165,7 +165,26 @@ public: Java: - +```Java +class Solution { + public int numTrees(int n) { + //初始化 dp 数组 + int[] dp = new int[n + 1]; + //初始化0个节点和1个节点的情况 + dp[0] = 1; + dp[1] = 1; + //遍历 + for (int i = 2; i <= n; i++) { + for (int j = 1; j <= i; j++) { + //对于第i个节点,需要考虑1作为根节点直到i作为根节点的情况,所以需要累加 + //一共i个节点,对于根节点j时,左子树的节点个数为j-1,右子树的节点个数为i-j + dp[i] += dp[j - 1] * dp[i - j]; + } + } + return dp[n]; + } +} +``` Python: From 231baca72ae08395e02602243f335004d9b63fe1 Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:48:45 +0800 Subject: [PATCH 072/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00096.=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0096.不同的二叉搜索树.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index 98c993e4..7dea8fb0 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -173,7 +173,6 @@ class Solution { //初始化0个节点和1个节点的情况 dp[0] = 1; dp[1] = 1; - //遍历 for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { //对于第i个节点,需要考虑1作为根节点直到i作为根节点的情况,所以需要累加 From b38296b0da0b8233eccd74c2ba2a4fc5054da90a Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:50:19 +0800 Subject: [PATCH 073/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00131.=E5=88=86?= =?UTF-8?q?=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 01ff35c5..9c86a3bc 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -250,7 +250,46 @@ public: Java: +```Java +class Solution { + List> lists = new ArrayList<>(); + Deque deque = new LinkedList<>(); + public List> partition(String s) { + backTracking(s, 0); + return lists; + } + + private void backTracking(String s, int startIndex) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + if (startIndex >= s.length()) { + lists.add(new ArrayList(deque)); + return; + } + for (int i = startIndex; i < s.length(); i++) { + //如果是回文子串,则记录 + if (isPalindrome(s, startIndex, i)) { + String str = s.substring(startIndex, i + 1); + deque.addLast(str); + } else { + continue; + } + //起始位置后移,保证不重复 + backTracking(s, i + 1); + deque.removeLast(); + } + } + //判断是否是回文串 + private boolean isPalindrome(String s, int startIndex, int end) { + for (int i = startIndex, j = end; i < j; i++, j--) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; + } +} +``` Python: From 7dc72358924792a6ab8a5ac9f028f4da4a16e01f Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:51:51 +0800 Subject: [PATCH 074/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00020.=E6=9C=89?= =?UTF-8?q?=E6=95=88=E7=9A=84=E6=8B=AC=E5=8F=B7=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index f2d78ade..4dae7072 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -138,7 +138,31 @@ public: Java: - +```Java +class Solution { + public boolean isValid(String s) { + Deque deque = new LinkedList<>(); + char ch; + for (int i = 0; i < s.length(); i++) { + ch = s.charAt(i); + //碰到左括号,就把相应的右括号入栈 + if (ch == '(') { + deque.push(')'); + }else if (ch == '{') { + deque.push('}'); + }else if (ch == '[') { + deque.push(']'); + } else if (deque.isEmpty() || deque.peek() != ch) { + return false; + }else {//如果是右括号判断是否和栈顶元素匹配 + deque.pop(); + } + } + //最后判断栈中元素是否匹配 + return deque.isEmpty(); + } +} +``` Python: ```python3 From 20a518c856320d0faa53e12664120bef5ba8a53c Mon Sep 17 00:00:00 2001 From: nanhuaibeian <49868746+nanhuaibeian@users.noreply.github.com> Date: Thu, 13 May 2021 09:53:02 +0800 Subject: [PATCH 075/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00349.=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86=20Java?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index c196b467..75ef9061 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -75,7 +75,37 @@ public: Java: +```Java +import java.util.HashSet; +import java.util.Set; +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) { + return new int[0]; + } + Set set1 = new HashSet<>(); + Set resSet = new HashSet<>(); + //遍历数组1 + for (int i : nums1) { + set1.add(i); + } + //遍历数组2的过程中判断哈希表中是否存在该元素 + for (int i : nums2) { + if (set1.contains(i)) { + resSet.add(i); + } + } + int[] resArr = new int[resSet.size()]; + int index = 0; + //将结果几何转为数组 + for (int i : resSet) { + resArr[index++] = i; + } + return resArr; + } +} +``` Python: From f854cbe7ae7e5daf796a9b3c27c05dd555327cab Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 10:07:16 +0800 Subject: [PATCH 076/177] =?UTF-8?q?Update=200450.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0450.删除二叉搜索树中的节点.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index ed0cb9d7..6e38b4fe 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -257,6 +257,44 @@ Python: Go: +```Go +func deleteNode(root *TreeNode, key int) *TreeNode { + if root==nil{ + return nil + } + if keyroot.Val{ + root.Right=deleteNode(root.Right,key) + return root + } + if root.Right==nil{ + return root.Left + } + if root.Left==nil{ + return root.Right + } + minnode:=root.Right + for minnode.Left!=nil{ + minnode=minnode.Left + } + root.Val=minnode.Val + root.Right=deleteNode1(root.Right) + return root +} + +func deleteNode1(root *TreeNode)*TreeNode{ + if root.Left==nil{ + pRight:=root.Right + root.Right=nil + return pRight + } + root.Left=deleteNode1(root.Left) + return root +} +``` From 770328ecd0673c2f5ba887f3282a75d8aebd3ab5 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 10:10:53 +0800 Subject: [PATCH 077/177] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 35 +++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 5d55910c..919ec7c7 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -361,7 +361,40 @@ Python: Go: - +```Go +func isBalanced(root *TreeNode) bool { + if root==nil{ + return true + } + if !isBalanced(root.Left) || !isBalanced(root.Right){ + return false + } + LeftH:=maxdepth(root.Left)+1 + RightH:=maxdepth(root.Right)+1 + if abs(LeftH-RightH)>1{ + return false + } + return true +} +func maxdepth(root *TreeNode)int{ + if root==nil{ + return 0 + } + return max(maxdepth(root.Left),maxdepth(root.Right))+1 +} +func max(a,b int)int{ + if a>b{ + return a + } + return b +} +func abs(a int)int{ + if a<0{ + return -a + } + return a +} +``` From f56d49a94f5d75abbe2f645212a77efd8b3bfa25 Mon Sep 17 00:00:00 2001 From: zqh1059405318 <1059405318@qq.com> Date: Thu, 13 May 2021 10:16:02 +0800 Subject: [PATCH 078/177] =?UTF-8?q?=E6=8F=90=E4=BA=A4242=E9=A2=98java?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index be553c5a..6c5a90ce 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -85,7 +85,24 @@ public: Java: +```java +public boolean isAnagram(String s, String t) { + int[] record = new int[26]; + for (char c : s.toCharArray()) { + record[c - 'a'] += 1; + } + for (char c : t.toCharArray()) { + record[c - 'a'] -= 1; + } + for (int i : record) { + if (i != 0) { + return false; + } + } + return true; +} +``` Python: From 645c93b688f33a69fb6220e35bd52959233e785f Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 10:19:25 +0800 Subject: [PATCH 079/177] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index baa3f435..ddd634b4 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -260,7 +260,25 @@ Python: Go: +```Go +import "math" +func isValidBST(root *TreeNode) bool { + if root == nil { + return true + } + return isBST(root, math.MinInt64, math.MaxFloat64) +} +func isBST(root *TreeNode, min, max int) bool { + if root == nil { + return true + } + if min >= root.Val || max <= root.Val { + return false + } + return isBST(root.Left, min, root.Val) && isBST(root.Right, root.Val, max) +} +``` From aeec6d756c01b8765b40fd9e106c7c9efdaa9fc5 Mon Sep 17 00:00:00 2001 From: simonhancrew <597494370@qq.com> Date: Thu, 13 May 2021 10:34:16 +0800 Subject: [PATCH 080/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00027.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0=20Python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 144cd5be..959474fc 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -124,9 +124,19 @@ public: Java: - Python: +```python +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + i,n = 0,len(nums) + for j in range(n): + if nums[j] != val: + nums[i] = nums[j] + i += 1 + return i +``` + Go: ```go @@ -162,4 +172,4 @@ var removeElement = (nums, val) => { * 作者微信:[程序员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 From 1613d2b4b0627c2b99c77c54590d77a1cb1ab3fc Mon Sep 17 00:00:00 2001 From: zqh1059405318 <1059405318@qq.com> Date: Thu, 13 May 2021 11:31:02 +0800 Subject: [PATCH 081/177] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=BA=86=E7=AC=AC202?= =?UTF-8?q?=EF=BC=8C242=EF=BC=8C349=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 21 ++++++++++++++++++ problems/0242.有效的字母异位词.md | 27 ++++++++++++----------- problems/0349.两个数组的交集.md | 24 ++++++++++++++++++++ 3 files changed, 59 insertions(+), 13 deletions(-) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index d6b1cdd2..8c0dd1e7 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -84,7 +84,28 @@ public: Java: +```java +class Solution { + public boolean isHappy(int n) { + Set record = new HashSet<>(); + while (n != 1 && !record.contains(n)) { + record.add(n); + n = getNextNumber(n); + } + return n == 1; + } + private int getNextNumber(int n) { + int res = 0; + while (n > 0) { + int temp = n % 10; + res += temp * temp; + n = n / 10; + } + return res; + } +} +``` Python: diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 6c5a90ce..89186620 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -86,22 +86,23 @@ public: Java: ```java -public boolean isAnagram(String s, String t) { - int[] record = new int[26]; - for (char c : s.toCharArray()) { - record[c - 'a'] += 1; - } - for (char c : t.toCharArray()) { - record[c - 'a'] -= 1; - } - for (int i : record) { - if (i != 0) { - return false; +class Solution { + public boolean isAnagram(String s, String t) { + int[] record = new int[26]; + for (char c : s.toCharArray()) { + record[c - 'a'] += 1; } + for (char c : t.toCharArray()) { + record[c - 'a'] -= 1; + } + for (int i : record) { + if (i != 0) { + return false; + } + } + return true; } - return true; } - ``` Python: diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index c196b467..195dbad5 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -75,7 +75,31 @@ public: Java: +```java +class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + Set record = new HashSet(); + Set unique = new HashSet(); + for (int num : nums1) { + record.add(num); + } + + for (int num : nums2) { + if (record.contains(num)) { + unique.add(num); + } + } + + int[] res = new int[unique.size()]; + int index = 0; + for (int num : unique) { + res[index++] = num; + } + return res; + } +} +``` Python: From 74e6290385025ea76c71687fcf343aa2c6cab624 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 12:53:02 +0800 Subject: [PATCH 082/177] =?UTF-8?q?Update=200078.=E5=AD=90=E9=9B=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 8c68843d..139d0ed5 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -183,7 +183,28 @@ Python: Go: - +```Go +var res [][]int +func subset(nums []int) [][]int { + res = make([][]int, 0) + sort.Ints(nums) + Dfs([]int{}, nums, 0) + return res +} +func Dfs(temp, nums []int, start int){ + tmp := make([]int, len(temp)) + copy(tmp, temp) + res = append(res, tmp) + for i := start; i < len(nums); i++{ + //if i>start&&nums[i]==nums[i-1]{ + // continue + //} + temp = append(temp, nums[i]) + Dfs(temp, nums, i+1) + temp = temp[:len(temp)-1] + } +} +``` From b5af23699accc90fd4179daa1790a891b08a9edf Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 13:01:07 +0800 Subject: [PATCH 083/177] =?UTF-8?q?Update=200344.=E5=8F=8D=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0344.反转字符串.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index ddb9805d..c2f16794 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -146,6 +146,17 @@ Python: Go: +```Go +func reverseString(s []byte) { + left:=0 + right:=len(s)-1 + for left Date: Thu, 13 May 2021 13:30:55 +0800 Subject: [PATCH 084/177] update 0404 --- problems/0101.对称二叉树.md | 8 ++++-- problems/0110.平衡二叉树.md | 8 ++++-- problems/0404.左叶子之和.md | 45 +++++++++++++++++++++++++++++++- 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 561d0470..b9e203e8 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -253,9 +253,13 @@ public: ## 其他语言版本 - Java: +```java +``` + + + Python: @@ -284,4 +288,4 @@ const check = (leftPtr, rightPtr) => { * 作者微信:[程序员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/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 5d55910c..ee215a68 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -353,9 +353,13 @@ public: ## 其他语言版本 - Java: +```java +``` + + + Python: @@ -369,4 +373,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/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 8ff2b320..da4ed666 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -159,9 +159,51 @@ public: ## 其他语言版本 - Java: +**递归** + +```java +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) return 0; + int leftValue = sumOfLeftLeaves(root.left); // 左 + int rightValue = sumOfLeftLeaves(root.right); // 右 + + int midValue = 0; + if (root.left != null && root.left.left == null && root.left.right == null) { // 中 + midValue = root.left.val; + } + int sum = midValue + leftValue + rightValue; + return sum; + } +} +``` + +**迭代** + +```java +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) return 0; + Stack stack = new Stack<> (); + stack.add(root); + int result = 0; + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + if (node.left != null && node.left.left == null && node.left.right == null) { + result += node.left.val; + } + if (node.right != null) stack.add(node.right); + if (node.left != null) stack.add(node.left); + } + return result; + } +} +``` + + + Python: @@ -176,3 +218,4 @@ Go: * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
+ From fa1b935e8e8296fc44ee684b9f1f1944b2261564 Mon Sep 17 00:00:00 2001 From: Tiansheng Sui Date: Wed, 12 May 2021 22:42:44 -0700 Subject: [PATCH 085/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00035.=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AEPython3=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index c351e365..e891e3c5 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -237,6 +237,22 @@ class Solution { Python: +```python3 +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + left, right = 0, len(nums) - 1 + + while left <= right: + middle = (left + right) // 2 + + if nums[middle] < target: + left = middle + 1 + elif nums[middle] > target: + right = middle - 1 + else: + return middle + return right + 1 +``` Go: From c3326eae14a66e42e6c007cdc8d2bed6f66d82c9 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 14:24:30 +0800 Subject: [PATCH 086/177] =?UTF-8?q?Update=200020.=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E6=8B=AC=E5=8F=B7.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index f2d78ade..ba50ad21 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -157,7 +157,26 @@ class Solution: ``` Go: +```Go +func isValid(s string) bool { + hash := map[byte]byte{')':'(', ']':'[', '}':'{'} + stack := make([]byte, 0) + if s == "" { + return true + } + for i := 0; i < len(s); i++ { + if s[i] == '(' || s[i] == '[' || s[i] == '{' { + stack = append(stack, s[i]) + } else if len(stack) > 0 && stack[len(stack)-1] == hash[s[i]] { + stack = stack[:len(stack)-1] + } else { + return false + } + } + return len(stack) == 0 +} +``` From 0354702fb54961781601787e6afa994cf6cfd99f Mon Sep 17 00:00:00 2001 From: Chengkq <1395092352@qq.com> Date: Thu, 13 May 2021 14:29:08 +0800 Subject: [PATCH 087/177] =?UTF-8?q?update=200404=20=E5=B7=A6=E5=8F=B6?= =?UTF-8?q?=E5=AD=90=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 5 ----- problems/0110.平衡二叉树.md | 5 ----- 2 files changed, 10 deletions(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index b9e203e8..535300af 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -255,11 +255,6 @@ public: Java: -```java -``` - - - Python: diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index ee215a68..3807aecc 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -355,11 +355,6 @@ public: Java: -```java -``` - - - Python: From b3168d09670dbb29007750d875c40b1f79f084e8 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Thu, 13 May 2021 18:04:01 +0800 Subject: [PATCH 088/177] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=E8=A1=A8=E8=BE=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/回溯算法理论基础.md | 4 ---- problems/数组总结篇.md | 3 --- problems/数组理论基础.md | 3 --- 3 files changed, 10 deletions(-) diff --git a/problems/回溯算法理论基础.md b/problems/回溯算法理论基础.md index 3aba34db..8bfd101c 100644 --- a/problems/回溯算法理论基础.md +++ b/problems/回溯算法理论基础.md @@ -163,10 +163,6 @@ void backtracking(参数) { -![](https://img-blog.csdnimg.cn/20210416110157800.png) - - - ## 其他语言版本 diff --git a/problems/数组总结篇.md b/problems/数组总结篇.md index 7c4c0fed..d8daa866 100644 --- a/problems/数组总结篇.md +++ b/problems/数组总结篇.md @@ -131,9 +131,6 @@ 最后,大家周末愉快! - - - ## 其他语言版本 diff --git a/problems/数组理论基础.md b/problems/数组理论基础.md index 457cd33e..c36cc8f7 100644 --- a/problems/数组理论基础.md +++ b/problems/数组理论基础.md @@ -144,9 +144,6 @@ Java的二维数组可能是如下排列的方式: 数组专题中讲解和相关题目已经有16道了,就不介绍太过题目了,因为数组是非常基础的数据结构后面很多专题还会用到数组,所以后面的题目依然会会间接练习数组的。 - -![](https://img-blog.csdnimg.cn/20210416110157800.png) - ## 其他语言版本 From d2dc3002903847d97f34707353da8bfe711953f2 Mon Sep 17 00:00:00 2001 From: suichenglixin <52021245+suichenglixin@users.noreply.github.com> Date: Thu, 13 May 2021 18:14:58 +0800 Subject: [PATCH 089/177] first commit --- problems/0056.合并区间.md | 30 ++++++++++++- problems/0070.爬楼梯完全背包版本.md | 18 +++++++- problems/0098.验证二叉搜索树.md | 15 ++++++- problems/0104.二叉树的最大深度.md | 14 +++++- ...序与后序遍历序列构造二叉树.md | 43 ++++++++++++++++++- ...将有序数组转换为二叉搜索树.md | 22 +++++++++- problems/0110.平衡二叉树.md | 25 ++++++++++- problems/0111.二叉树的最小深度.md | 14 ++++++ problems/0112.路径总和.md | 20 ++++++++- .../0122.买卖股票的最佳时机II.md | 20 ++++++++- problems/0134.加油站.md | 23 +++++++++- problems/0135.分发糖果.md | 30 ++++++++++++- problems/0139.单词拆分.md | 18 +++++++- problems/0206.翻转链表.md | 20 ++++++++- problems/0209.长度最小的子数组.md | 21 ++++++++- problems/0216.组合总和III.md | 25 ++++++++++- .../0222.完全二叉树的节点个数.md | 13 +++++- problems/0226.翻转二叉树.md | 20 ++++++++- ...35.二叉搜索树的最近公共祖先.md | 21 +++++++-- .../0236.二叉树的最近公共祖先.md | 17 +++++++- problems/0242.有效的字母异位词.md | 21 ++++++++- problems/0257.二叉树的所有路径.md | 35 ++++++++++++++- problems/0404.左叶子之和.md | 17 +++++++- problems/0406.根据身高重建队列.md | 25 ++++++++++- problems/0435.无重叠区间.md | 29 ++++++++++++- .../0450.删除二叉搜索树中的节点.md | 29 ++++++++++++- .../0452.用最少数量的箭引爆气球.md | 27 +++++++++++- problems/0455.分发饼干.md | 22 ++++++++-- problems/0491.递增子序列.md | 28 +++++++++++- problems/0494.目标和.md | 21 ++++++++- problems/0501.二叉搜索树中的众数.md | 42 +++++++++++++++++- problems/0513.找树左下角的值.md | 24 ++++++++++- .../0530.二叉搜索树的最小绝对差.md | 21 ++++++++- ...38.把二叉搜索树转换为累加树.md | 18 +++++++- problems/0617.合并二叉树.md | 14 +++++- problems/0654.最大二叉树.md | 26 ++++++++++- problems/0669.修剪二叉搜索树.md | 25 ++++++++++- problems/0700.二叉搜索树中的搜索.md | 13 +++++- .../0701.二叉搜索树中的插入操作.md | 28 +++++++++++- ...买卖股票的最佳时机含手续费.md | 18 +++++++- problems/0738.单调递增的数字.md | 20 ++++++++- problems/0763.划分字母区间.md | 23 +++++++++- problems/0860.柠檬水找零.md | 28 +++++++++++- problems/0968.监控二叉树.md | 29 ++++++++++++- ...1005.K次取反后最大化的数组和.md | 26 ++++++++++- 45 files changed, 981 insertions(+), 57 deletions(-) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index f939325f..e84a1634 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -137,7 +137,35 @@ public: Java: +```java +class Solution { + public int[][] merge(int[][] intervals) { + List res = new LinkedList<>(); + Arrays.sort(intervals, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] != o2[0]) { + return Integer.compare(o1[0],o2[0]); + } else { + return Integer.compare(o1[1],o2[1]); + } + } + }); + int start = intervals[0][0]; + for (int i = 1; i < intervals.length; i++) { + if (intervals[i][0] > intervals[i - 1][1]) { + res.add(new int[]{start, intervals[i - 1][1]}); + start = intervals[i][0]; + } else { + intervals[i][1] = Math.max(intervals[i][1], intervals[i - 1][1]); + } + } + res.add(new int[]{start, intervals[intervals.length - 1][1]}); + return res.toArray(new int[res.size()][]); + } +} +``` Python: @@ -151,4 +179,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/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index beda45d5..d6b12450 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -127,7 +127,23 @@ public: Java: +```java +class Solution { + public int climbStairs(int n) { + int[] dp = new int[n + 1]; + int[] weight = {1,2}; + dp[0] = 1; + for (int i = 0; i <= n; i++) { + for (int j = 0; j < weight.length; j++) { + if (i >= weight[j]) dp[i] += dp[i - weight[j]]; + } + } + + return dp[n]; + } +} +``` Python: @@ -141,4 +157,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/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index baa3f435..524d6a07 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -254,6 +254,19 @@ public: Java: +```java +class Solution { + public boolean isValidBST(TreeNode root) { + return isValidBST_2(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + public boolean isValidBST_2 (TreeNode root, long lo, long hi) { + if (root == null) return true; + if (root.val >= hi || root.val <= lo) return false; + return isValidBST_2(root.left,lo,root.val) && isValidBST_2(root.right,root.val,hi); + } +} +``` Python: @@ -268,4 +281,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/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 814beb55..bf6d40a3 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -231,6 +231,18 @@ public: Java: +```java +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + int leftdeep = maxDepth(root.left); + int rightdeep = maxDepth(root.right); + return 1+Math.max(leftdeep,rightdeep); + } +} +``` Python: @@ -245,4 +257,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/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index f1f30b71..907f91f6 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -582,6 +582,47 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 Java: +```java +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (inorder.length == 0 || postorder.length == 0) return null; + return buildTree(inorder, postorder,0,inorder.length,0,postorder.length); + } + + private TreeNode buildTree(int[] inorder, int[] postorder, int infrom, int into, + int postfrom, int postto) { + if (postfrom == postto) return null; + + int rootValue = postorder[postto - 1]; + TreeNode root = new TreeNode(rootValue); + + if (postfrom + 1 == postto) return root; + + int splitNum = postto - 1; + for (int i = infrom; i < into; i++) { + if (inorder[i] == rootValue) { + splitNum = i; + break; + } + } + + int inLeftBegin = infrom; + int inLeftEnd = splitNum; + int inRightBegin = splitNum + 1; + int inRightEnd = into; + + int postLeftBegin = postfrom; + int postLeftEnd = postLeftBegin + (splitNum - inLeftBegin); + int postRightBegin = postLeftBegin + (splitNum - inLeftBegin); + int postRightEnd = postto - 1; + + root.left = buildTree(inorder,postorder,inLeftBegin,inLeftEnd,postLeftBegin,postLeftEnd); + root.right = buildTree(inorder,postorder,inRightBegin,inRightEnd,postRightBegin,postRightEnd); + + return root; + } +} +``` Python: @@ -596,4 +637,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/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 12d47e6a..952dc687 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -209,6 +209,26 @@ public: Java: +```java +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + return sortArr(nums,0,nums.length); + } + + private TreeNode sortArr(int[] nums, int lo, int hi) { + if (lo == hi) return null; + int rootIdx = (lo + hi)/2; + + int rootValue = nums[rootIdx]; + TreeNode root = new TreeNode(rootValue); + + root.left = sortArr(nums,lo,rootIdx); + root.right = sortArr(nums,rootIdx+1,hi); + + return root; + } +} +``` Python: @@ -223,4 +243,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/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 5d55910c..b8a373fd 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -355,6 +355,29 @@ public: Java: +```java +class Solution { + boolean flag = true; + public boolean isBalanced(TreeNode root) { + high(root); + return flag; + } + + private int high (TreeNode root) { + if (root == null) return 0; + if (flag) { + int left = high(root.left); + int right = high(root.right); + + if (Math.abs(left - right) > 1) flag = false; + + return Math.max(left,right) + 1; + } else { + return -1; + } + } +} +``` Python: @@ -369,4 +392,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/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 6c6b4632..4f79b334 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -194,6 +194,20 @@ public: Java: +```java +class Solution { + public int minDepth(TreeNode root) { + if (root == null) return 0; + int leftDeep = minDepth(root.left); + int rightDeep = minDepth(root.right); + + if (root.left == null && root.right != null) return 1+rightDeep; + if (root.left != null && root.right == null) return 1+leftDeep; + + return Math.min(leftDeep,rightDeep)+1; + } +} +``` Python: diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 718a2f5b..deee84cf 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -305,6 +305,24 @@ public: Java: +```java +class Solution { + private boolean flag = false; + public boolean hasPathSum(TreeNode root, int targetSum) { + has_2(root,targetSum); + return flag; + } + + public void has_2 (TreeNode root, int count) { + if (root == null) return; + if (root.left == null && root.right == null && count == root.val) { + flag = true; + } + if (root.left != null) has_2(root.left,count - root.val); + if (root.right != null) has_2(root.right,count - root.val); + } +} +``` Python: @@ -387,4 +405,4 @@ let pathSum = function (root, targetSum) { * 作者微信:[程序员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/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 1a9b4f7f..0e770972 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -135,7 +135,23 @@ public: Java: - +```java +class Solution { + public int maxProfit(int[] prices) { + int sum = 0; + int profit = 0; + int buy = prices[0]; + for (int i = 1; i < prices.length; i++) { + profit = prices[i] - buy; + if (profit > 0) { + sum += profit; + } + buy = prices[i]; + } + return sum; + } +} +``` Python: @@ -149,4 +165,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/0134.加油站.md b/problems/0134.加油站.md index 9c72e84d..393e4627 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -199,7 +199,28 @@ public: Java: +```java +class Solution { + public int canCompleteCircuit(int[] gas, int[] cost) { + int sum = 0; + int min = 0; + for (int i = 0; i < gas.length; i++) { + sum += (gas[i] - cost[i]); + min = Math.min(sum, min); + } + if (sum < 0) return -1; + if (min >= 0) return 0; + + for (int i = gas.length - 1; i > 0; i--) { + min += (gas[i] - cost[i]); + if (min >= 0) return i; + } + + return -1; + } +} +``` Python: @@ -213,4 +234,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/0135.分发糖果.md b/problems/0135.分发糖果.md index 0595cff6..fedf8765 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -130,7 +130,35 @@ public: Java: +```java +class Solution { + public int candy(int[] ratings) { + int[] candy = new int[ratings.length]; + for (int i = 0; i < candy.length; i++) { + candy[i] = 1; + } + for (int i = 1; i < ratings.length; i++) { + if (ratings[i] > ratings[i - 1]) { + candy[i] = candy[i - 1] + 1; + } + } + + for (int i = ratings.length - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1]) { + candy[i] = Math.max(candy[i],candy[i + 1] + 1); + } + } + + int count = 0; + for (int i = 0; i < candy.length; i++) { + count += candy[i]; + } + + return count; + } +} +``` Python: @@ -144,4 +172,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/0139.单词拆分.md b/problems/0139.单词拆分.md index ec996565..c6d8e43b 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -232,7 +232,23 @@ public: Java: +```java +class Solution { + public boolean wordBreak(String s, List wordDict) { + boolean[] valid = new boolean[s.length() + 1]; + valid[0] = true; + for (int i = 1; i <= s.length(); i++) { + for (int j = 0; j < i; j++) { + if (wordDict.contains(s.substring(j,i)) && valid[j]) { + valid[i] = true; + } + } + } + return valid[s.length()]; + } +} +``` Python: @@ -246,4 +262,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/0206.翻转链表.md b/problems/0206.翻转链表.md index b465cdf9..1bff0b74 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -102,6 +102,24 @@ public: Java: +```java +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) return head; + ListNode last = head; + ListNode cur = head.next; + head.next = null; + while (cur.next != null) { + ListNode tmp = cur.next; + cur.next = last; + last = cur; + cur = tmp; + } + cur.next = last; + return cur; + } +} +``` Python: @@ -116,4 +134,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/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 1b00c4e3..53e03077 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -148,7 +148,24 @@ class Solution: Java: - +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + Integer size = Integer.MAX_VALUE; + int from = 0; + int to = 0; + int sum = 0; + while (to < nums.length) { + sum += nums[to++]; + while (sum >= target) { + size = Math.min(size,to - from); + sum -= nums[from++]; + } + } + return size == Integer.MAX_VALUE ? 0 : size; + } +} +``` Python: @@ -177,4 +194,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/0216.组合总和III.md b/problems/0216.组合总和III.md index 11a8eb8f..351b98c9 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -227,7 +227,30 @@ public: Java: +```java +class Solution { + private List path = new ArrayList<>(); + private List> res = new ArrayList<>(); + public List> combinationSum3(int k, int n) { + backtracking(k, n, 1); + return res; + } + private void backtracking (int k, int count, int start) { + if (count == 0 && k == 0) { + res.add(new ArrayList<>(path)); + return; + } + + for (int i = start; i <= 9; i++) { + path.add(i); + backtracking(k - 1, count - i, i + 1); + path.remove(path.size() - 1); + } + } + +} +``` Python: @@ -241,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/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 367fa717..991d21f3 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -194,7 +194,18 @@ public: Java: +```java +class Solution { + public int countNodes(TreeNode root) { + if (root == null) return 0; + int leftnum = countNodes(root.left); + int rightnum = countNodes(root.right); + + return leftnum + rightnum + 1; + } +} +``` Python: @@ -208,4 +219,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/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index afc1f144..2fa6dc06 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -203,7 +203,25 @@ public: Java: +```java +class Solution { + public TreeNode invertTree(TreeNode root) { + invert(root); + return root; + } + private static void invert (TreeNode root) { + if (root == null) return; + + invert(root.left); + TreeNode t = root.left; + root.left = root.right; + root.right = t; + + invert(root.left); + } +} +``` Python: @@ -217,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/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index cb9de8b0..93642de5 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -29,7 +29,7 @@ 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 输出: 2 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。 -  + 说明: @@ -229,7 +229,22 @@ public: Java: - +```java +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + while (true) { + if (root.val > p.val && root.val > q.val) { + root = root.left; + } else if (root.val < p.val && root.val < q.val) { + root = root.right; + } else { + break; + } + } + return root; + } +} +``` Python: @@ -243,4 +258,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 17096d48..9a8c3948 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -223,7 +223,20 @@ public: Java: - +```java +class Solution { + TreeNode pre; + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root.val == p.val ||root.val == q.val) return root; + TreeNode left = lowestCommonAncestor(root.left,p,q); + TreeNode right = lowestCommonAncestor(root.right,p,q); + if (left != null && right != null) return root; + else if (left == null && right != null) return right; + else if (left != null && right == null) return left; + else return null; + } +} +``` Python: @@ -237,4 +250,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/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index be553c5a..49798cce 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -85,7 +85,26 @@ public: Java: +```java +class Solution { + public boolean isAnagram(String s, String t) { + int[] strMap = new int[123]; + for (int i = 0; i < s.length(); i++) { + strMap[s.charAt(i) + 0]++; + } + for (int i = 0; i < t.length(); i++) { + strMap[t.charAt(i) + 0]--; + } + + for (int i = 90; i < 123; i++) { + if (strMap[i] != 0) return false; + } + + return true; + } +} +``` Python: @@ -120,4 +139,4 @@ func isAnagram(s string, t string) bool { * 作者微信:[程序员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/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index a104b27c..f6515a78 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -280,8 +280,39 @@ public: ## 其他语言版本 - Java: +```java +class Solution { + public List binaryTreePaths(TreeNode root) { + LinkedList stack = new LinkedList<>(); + List list = new LinkedList<>(); + TreePaths(root,stack,list); + return list; + } + + private static void TreePaths (TreeNode root, LinkedList path, List res) { + path.add(root); + if (root.left == null && root.right == null) { + StringBuilder sb = new StringBuilder(); + for (TreeNode n : path) { + sb.append(n.val); + sb.append("->"); + } + sb.delete(sb.length()-2,sb.length()); + res.add(sb.toString()); + return; + } + if (root.left != null) { + TreePaths(root.left, path, res); + path.removeLast(); + } + if (root.right != null) { + TreePaths(root.right, path, res); + path.removeLast(); + } + } +} +``` Python: @@ -296,4 +327,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/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 8ff2b320..16c8fa67 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -161,7 +161,20 @@ public: Java: - +```java +class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if (root == null) return 0; + int sum = 0; + if (root.left != null && root.left.left == null && root.left.right == null) { + sum = root.left.val; + } + int left = sumOfLeftLeaves(root.left); + int right = sumOfLeftLeaves(root.right); + return left + right + sum; + } +} +``` Python: @@ -175,4 +188,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/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index b5260a8c..2ef0a2fd 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -185,7 +185,30 @@ public: Java: +```java +class Solution { + public int[][] reconstructQueue(int[][] people) { + Arrays.sort(people, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] != o2[0]) { + return Integer.compare(o2[0],o1[0]); + } else { + return Integer.compare(o1[1],o2[1]); + } + } + }); + LinkedList que = new LinkedList<>(); + + for (int[] p : people) { + que.add(p[1],p); + } + + return que.toArray(new int[people.length][]); + } +} +``` Python: @@ -199,4 +222,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/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 3df496f4..4341f3b8 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -182,7 +182,34 @@ public: Java: +```java +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + if (intervals.length < 2) return 0; + Arrays.sort(intervals, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] != o2[0]) { + return Integer.compare(o1[1],o2[1]); + } else { + return Integer.compare(o2[0],o1[0]); + } + } + }); + int count = 0; + int edge = intervals[0][1]; + for (int i = 1; i < intervals.length; i++) { + if (intervals[i][0] < edge) { + count++; + } else { + edge = intervals[i][1]; + } + } + return count; + } +} +``` Python: @@ -196,4 +223,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 ed0cb9d7..2670435e 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -251,7 +251,34 @@ public: Java: +```java +class Solution { + public TreeNode deleteNode(TreeNode root, int key) { + root = delete(root,key); + return root; + } + private TreeNode delete(TreeNode root, int key) { + if (root == null) return null; + + if (root.val > key) { + root.left = delete(root.left,key); + } else if (root.val < key) { + root.right = delete(root.right,key); + } else { + if (root.left == null) return root.right; + if (root.right == null) return root.left; + TreeNode tmp = root.right; + while (tmp.left != null) { + tmp = tmp.left; + } + root.val = tmp.val; + root.right = delete(root.right,tmp.val); + } + return root; + } +} +``` Python: @@ -265,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/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index 7372ea92..f62fb153 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -139,7 +139,32 @@ public: Java: +```java +class Solution { + public int findMinArrowShots(int[][] points) { + Arrays.sort(points, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if (o1[0] != o2[0]) { + return Integer.compare(o1[0],o2[0]); + } else { + return Integer.compare(o1[0],o2[0]); + } + } + }); + int count = 1; + for (int i = 1; i < points.length; i++) { + if (points[i][0] > points[i - 1][1]) { + count++; + } else { + points[i][1] = Math.min(points[i][1],points[i - 1][1]); + } + } + return count; + } +} +``` Python: @@ -153,4 +178,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/0455.分发饼干.md b/problems/0455.分发饼干.md index ca3eba74..f57a7fa6 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -30,7 +30,7 @@ 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 你拥有的饼干数量和尺寸都足以让所有孩子满足。 所以你应该输出2. -  + 提示: * 1 <= g.length <= 3 * 10^4 @@ -115,7 +115,23 @@ public: Java: - +```java +class Solution { + public int findContentChildren(int[] g, int[] s) { + Arrays.sort(g); + Arrays.sort(s); + int start = 0; + int count = 0; + for (int i = 0; i < s.length && start < g.length; i++) { + if (s[i] >= g[start]) { + start++; + count++; + } + } + return count; + } +} +``` Python: @@ -129,4 +145,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/0491.递增子序列.md b/problems/0491.递增子序列.md index 5deec0ee..5e36d6be 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -200,6 +200,32 @@ public: Java: +```java +class Solution { + private List path = new ArrayList<>(); + private List> res = new ArrayList<>(); + public List> findSubsequences(int[] nums) { + backtracking(nums,0); + return res; + } + + private void backtracking (int[] nums, int start) { + if (path.size() > 1) { + res.add(new ArrayList<>(path)); + } + + int[] used = new int[201]; + for (int i = start; i < nums.length; i++) { + if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || + (used[nums[i] + 100] == 1)) continue; + used[nums[i] + 100] = 1; + path.add(nums[i]); + backtracking(nums, i + 1); + path.remove(path.size() - 1); + } + } +} +``` Python: @@ -214,4 +240,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/0494.目标和.md b/problems/0494.目标和.md index 2fb2a5eb..1782c88c 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -241,7 +241,24 @@ dp[j] += dp[j - nums[i]]; Java: - +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int sum = 0; + for (int i = 0; i < nums.length; i++) sum += nums[i]; + if ((target + sum) % 2 != 0) return 0; + int size = (target + sum) / 2; + int[] dp = new int[size + 1]; + dp[0] = 1; + for (int i = 0; i < nums.length; i++) { + for (int j = size; j >= nums[i]; j--) { + dp[j] += dp[j - nums[i]]; + } + } + return dp[size]; + } +} +``` Python: @@ -255,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 0e8c0d0e..b555692f 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -344,7 +344,47 @@ public: Java: +```java +class Solution { + private LinkedList list = new LinkedList<>(); + private int currentValue; + private int count; + private int maxCount; + public int[] findMode(TreeNode root) { + count = 0; + maxCount = 0; + currentValue = root.val; + findModeTrl(root); + int[] res = new int[list.size()]; + for (int i = 0; i < res.length; i++) { + res[i] = list.get(i); + } + return res; + } + private void findModeTrl (TreeNode root) { + if (root == null) return; + findModeTrl(root.left); + if (root.val == currentValue) { + count++; + } else { + currentValue = root.val; + count = 1; + } + + if (count == maxCount) { + list.add(root.val); + } else if (count > maxCount) { + maxCount = count; + list.clear(); + list.add(currentValue); + } + + findModeTrl(root.right); + } +} + +``` Python: @@ -358,4 +398,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/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 19c870c3..e3be8905 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -217,7 +217,29 @@ public: Java: +```java +class Solution { + private int Deep = -1; + private int value = 0; + public int findBottomLeftValue(TreeNode root) { + value = root.val; + findLeftValue(root,0); + return value; + } + private void findLeftValue (TreeNode root,int deep) { + if (root == null) return; + if (root.left == null && root.right == null) { + if (deep > Deep) { + value = root.val; + Deep = deep; + } + } + if (root.left != null) findLeftValue(root.left,deep + 1); + if (root.right != null) findLeftValue(root.right,deep + 1); + } +} +``` Python: @@ -231,4 +253,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/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index d5abc692..87ed222e 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -151,7 +151,26 @@ public: Java: +```java +class Solution { + private TreeNode pre = null; + private int res = Integer.MAX_VALUE; + public int getMinimumDifference(TreeNode root) { + getMiniDiff(root); + return res; + } + private void getMiniDiff (TreeNode root) { + if (root == null) return; + getMiniDiff(root.left); + if (pre != null) { + res = Math.min(root.val - pre.val,res); + } + pre = root; + getMiniDiff(root.right); + } +} +``` Python: @@ -165,4 +184,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/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index a5f4c43c..a44452e2 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -173,7 +173,23 @@ public: Java: +```java +class Solution { + private int count = 0; + public TreeNode convertBST(TreeNode root) { + convert(root); + return root; + } + private void convert (TreeNode root) { + if (root == null) return; + convert(root.right); + count += root.val; + root.val = count; + convert(root.left); + } +} +``` Python: @@ -187,4 +203,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/0617.合并二叉树.md b/problems/0617.合并二叉树.md index adc0703b..9836f568 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -256,7 +256,19 @@ public: Java: +```java +class Solution { + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) return root2; + if (root2 == null) return root1; + TreeNode newRoot = new TreeNode(root1.val + root2.val); + newRoot.left = mergeTrees(root1.left,root2.left); + newRoot.right = mergeTrees(root1.right,root2.right); + return newRoot; + } +} +``` Python: @@ -270,4 +282,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/0654.最大二叉树.md b/problems/0654.最大二叉树.md index af133e0c..ef417078 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -224,7 +224,31 @@ root->right = traversal(nums, maxValueIndex + 1, right); Java: +```java +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + if (nums.length == 0) return null; + return constructMaximumBinaryTree(nums,0,nums.length); + } + private TreeNode constructMaximumBinaryTree(int[] nums, int begin, int end) { + if (begin == end) return null; + + int rootValue = nums[begin]; + int index = begin; + for (int i = begin; i < end ; i++) { + if (nums[i] > rootValue) { + rootValue = nums[i]; + index = i; + } + } + TreeNode root = new TreeNode(rootValue); + root.left = constructMaximumBinaryTree(nums, begin,index); + root.right = constructMaximumBinaryTree(nums,index+1,end); + return root; + } +} +``` Python: @@ -238,4 +262,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/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 41f684f4..442ea8fb 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -242,7 +242,30 @@ public: Java: +```java +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + root = trim(root,low,high); + return root; + } + private static TreeNode trim(TreeNode root,int low, int high) { + if (root == null ) return null; + if (root.val < low) { + return trim(root.right,low,high); + } + if (root.val > high) { + return trim(root.left,low,high); + } + + root.left = trim(root.left,low,high); + root.right = trim(root.right,low,high); + + return root; + } +} + +``` Python: @@ -256,4 +279,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/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 5c1cdfdf..74a8c073 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -142,7 +142,16 @@ public: Java: - +```java +class Solution { + public TreeNode searchBST(TreeNode root, int val) { + if (root == null) return null; + if (root.val == val) return root; + if (root.val > val) return searchBST(root.left, val); + return searchBST(root.right, val); + } +} +``` Python: @@ -156,4 +165,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/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 760509d9..05f5aa02 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -16,7 +16,7 @@ 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。 ![701.二叉搜索树中的插入操作](https://img-blog.csdnimg.cn/20201019173259554.png) -  + 提示: * 给定的树上的节点数介于 0 和 10^4 之间 @@ -208,6 +208,30 @@ public: Java: +```java +class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { + if (root == null) return new TreeNode(val); + TreeNode newRoot = root; + TreeNode pre = root; + while (root != null) { + pre = root; + if (root.val > val) { + root = root.left; + } else if (root.val < val) { + root = root.right; + } + } + if (pre.val > val) { + pre.left = new TreeNode(val); + } else { + pre.right = new TreeNode(val); + } + + return newRoot; + } +} +``` Python: @@ -222,4 +246,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/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index 92697a64..86954c14 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -156,7 +156,23 @@ public: Java: - +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int buy = prices[0] + fee; + int sum = 0; + for (int p : prices) { + if (p + fee < buy) { + buy = p + fee; + } else if (p > buy){ + sum += p - buy; + buy = p; + } + } + return sum; + } +} +``` Python: diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index d423d4d6..dc136028 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -125,6 +125,24 @@ public: Java: +```java +class Solution { + public int monotoneIncreasingDigits(int N) { + String[] strings = (N + "").split(""); + int start = strings.length; + for (int i = strings.length - 1; i > 0; i--) { + if (Integer.parseInt(strings[i]) < Integer.parseInt(strings[i - 1])) { + strings[i - 1] = (Integer.parseInt(strings[i - 1]) - 1) + ""; + start = i; + } + } + for (int i = start; i < strings.length; i++) { + strings[i] = "9"; + } + return Integer.parseInt(String.join("",strings)); + } +} +``` Python: @@ -139,4 +157,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/0763.划分字母区间.md b/problems/0763.划分字母区间.md index 1b93edf7..c1474280 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -84,7 +84,28 @@ public: Java: - +```java +class Solution { + public List partitionLabels(String S) { + List list = new LinkedList<>(); + int[] edge = new int[123]; + char[] chars = S.toCharArray(); + for (int i = 0; i < chars.length; i++) { + edge[chars[i] - 0] = i; + } + int idx = 0; + int last = -1; + for (int i = 0; i < chars.length; i++) { + idx = Math.max(idx,edge[chars[i] - 0]); + if (i == idx) { + list.add(i - last); + last = i; + } + } + return list; + } +} +``` Python: diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index c718b0cd..bf8a3776 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -127,7 +127,33 @@ public: Java: +```java +class Solution { + public boolean lemonadeChange(int[] bills) { + int cash_5 = 0; + int cash_10 = 0; + for (int i = 0; i < bills.length; i++) { + if (bills[i] == 5) { + cash_5++; + } else if (bills[i] == 10) { + cash_5--; + cash_10++; + } else if (bills[i] == 20) { + if (cash_10 > 0) { + cash_10--; + cash_5--; + } else { + cash_5 -= 3; + } + } + if (cash_5 < 0 || cash_10 < 0) return false; + } + + return true; + } +} +``` Python: @@ -141,4 +167,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/0968.监控二叉树.md b/problems/0968.监控二叉树.md index ab2bd2e5..e541ba13 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -316,6 +316,33 @@ public: Java: +```java +class Solution { + private int count = 0; + public int minCameraCover(TreeNode root) { + if (trval(root) == 0) count++; + return count; + } + + private int trval(TreeNode root) { + if (root == null) return -1; + + int left = trval(root.left); + int right = trval(root.right); + + if (left == 0 || right == 0) { + count++; + return 2; + } + + if (left == 2 || right == 2) { + return 1; + } + + return 0; + } +} +``` Python: @@ -330,4 +357,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/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index b2073e14..1653201e 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -29,7 +29,7 @@ 输入:A = [2,-3,-1,5,-4], K = 2 输出:13 解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。 -  + 提示: * 1 <= A.length <= 10000 @@ -99,7 +99,29 @@ public: Java: +```java +class Solution { + public int largestSumAfterKNegations(int[] A, int K) { + if (A.length == 1) return A[0]; + Arrays.sort(A); + int sum = 0; + int idx = 0; + for (int i = 0; i < K; i++) { + if (i < A.length - 1 && A[idx] < 0) { + A[idx] = -A[idx]; + if (A[idx] >= Math.abs(A[idx + 1])) idx++; + continue; + } + A[idx] = -A[idx]; + } + for (int i = 0; i < A.length; i++) { + sum += A[i]; + } + return sum; + } +} +``` Python: @@ -113,4 +135,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 From 3ca406df3aeb37f03719b73430e8ce00b4aec7cb Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 18:25:55 +0800 Subject: [PATCH 090/177] =?UTF-8?q?Update=200090.=E5=AD=90=E9=9B=86II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index cc5fd571..5782f55d 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -178,7 +178,30 @@ Python: Go: +```Go +var res[][]int +func subsetsWithDup(nums []int)[][]int { + res=make([][]int,0) + sort.Ints(nums) + dfs([]int{},nums,0) + return res +} +func dfs(temp, num []int, start int) { + tmp:=make([]int,len(temp)) + copy(tmp,temp) + + res=append(res,tmp) + for i:=start;istart&&num[i]==num[i-1]{ + continue + } + temp=append(temp,num[i]) + dfs(temp,num,i+1) + temp=temp[:len(temp)-1] + } +} +``` From e4087dfe785834a5e36e6df4ca08afa64ce52ef0 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Thu, 13 May 2021 18:38:46 +0800 Subject: [PATCH 091/177] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index ec1335c6..f5626ea0 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -207,7 +207,7 @@ Java: Python: - +Go: ```Go func invertTree(root *TreeNode) *TreeNode { if root ==nil{ From b52d12bd3734b43f6ecaa9e9a491c3e4d6e939f7 Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 19:06:13 +0800 Subject: [PATCH 092/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A01143.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E5=85=AC=E5=85=B1=E5=AD=90=E5=BA=8F=E5=88=97=20Java/P?= =?UTF-8?q?ython=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1143.最长公共子序列.md | 38 ++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index 0664b0d9..19f4cc72 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -31,7 +31,7 @@ 输入:text1 = "abc", text2 = "def" 输出:0 解释:两个字符串没有公共子序列,返回 0。 -  + 提示: * 1 <= text1.length <= 1000 * 1 <= text2.length <= 1000 @@ -126,12 +126,44 @@ public: ## 其他语言版本 - Java: +```java +class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int[][] dp = new int[text1.length() + 1][text2.length() + 1]; // 先对dp数组做初始化操作 + for (int i = 1 ; i <= text1.length() ; i++) { + char char1 = text1.charAt(i - 1); + for (int j = 1; j <= text2.length(); j++) { + char char2 = text2.charAt(j - 1); + if (char1 == char2) { // 开始列出状态转移方程 + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[text1.length()][text2.length()]; + } +} +``` Python: +```python +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + len1, len2 = len(text1)+1, len(text2)+1 + dp = [[0 for _ in range(len1)] for _ in range(len2)] # 先对dp数组做初始化操作 + for i in range(1, len2): + for j in range(1, len1): # 开始列出状态转移方程 + if text1[j-1] == text2[i-1]: + dp[i][j] = dp[i-1][j-1]+1 + else: + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + return dp[-1][-1] +``` + Go: @@ -142,4 +174,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 From 7e389a8dcac9d5588b643961eedd35695e8baace Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 19:16:54 +0800 Subject: [PATCH 093/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BEJava=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 45 ++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index bb013d95..c7207364 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -23,7 +23,7 @@ 输入: nums = [-1,0,3,5,9,12], target = 2 输出: -1 解释: 2 不存在 nums 中因此返回 -1 -  + 提示: * 你可以假设 nums 中的所有元素是不重复的。 @@ -146,11 +146,50 @@ public: ## 其他语言版本 - Java: +(版本一)左闭右闭区间 + +```java +class Solution { + public int search(int[] nums, int target) { + int left = 0, right = nums.length - 1; + while (left <= right) { + int mid = left + ((right - left) >> 1); + if (nums[mid] == target) + return mid; + else if (nums[mid] < target) + left = mid + 1; + else if (nums[mid] > target) + right = mid - 1; + } + return -1; + } +} +``` + +(版本二)左闭右开区间 + +```java +class Solution { + public int search(int[] nums, int target) { + int left = 0, right = nums.length; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (nums[mid] == target) + return mid; + else if (nums[mid] < target) + left = mid + 1; + else if (nums[mid] > target) + right = mid; + } + return -1; + } +} +``` Python: + ```python3 class Solution: def search(self, nums: List[int], target: int) -> int: @@ -178,4 +217,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 From 279daa736f248cc260531be269c93d1165be4507 Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 19:38:47 +0800 Subject: [PATCH 094/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0701.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92?= =?UTF-8?q?=E5=85=A5=E6=93=8D=E4=BD=9C=20Java/Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0701.二叉搜索树中的插入操作.md | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 760509d9..26c6bb9c 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -16,7 +16,7 @@ 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。 ![701.二叉搜索树中的插入操作](https://img-blog.csdnimg.cn/20201019173259554.png) -  + 提示: * 给定的树上的节点数介于 0 和 10^4 之间 @@ -206,12 +206,45 @@ public: ## 其他语言版本 - Java: +递归法 + +```java +class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { + return buildTree(root, val); + } + + public TreeNode buildTree(TreeNode root, int val){ + if (root == null) // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。 + return new TreeNode(val); + if (root.val < val){ + root.right = buildTree(root.right, val); // 递归创建右子树 + }else if (root.val > val){ + root.left = buildTree(root.left, val); // 递归创建左子树 + } + return root; + } +} +``` Python: +递归法 + +```python +class Solution: + def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: + if root is None: + return TreeNode(val) # 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。 + if root.val < val: + root.right = self.insertIntoBST(root.right, val) # 递归创建右子树 + if root.val > val: + root.left = self.insertIntoBST(root.left, val) # 递归创建左子树 + return root +``` + Go: @@ -222,4 +255,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 From 6279c982c877aed580d51cdbb46fd110bf157b42 Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 19:58:49 +0800 Subject: [PATCH 095/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0700.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=20Java/Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0700.二叉搜索树中的搜索.md | 53 +++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 5c1cdfdf..659aec80 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -140,12 +140,61 @@ public: ## 其他语言版本 - Java: +递归法: + +```java +class Solution { + public TreeNode searchBST(TreeNode root, int val) { + if (root == null) return null; + if (root.val == val) return root; + else if (root.val > val) return searchBST(root.left, val); + else return searchBST(root.right, val); + } +} +``` + +迭代法: + +```java +class Solution { + public TreeNode searchBST(TreeNode root, int val) { + while (root != null) + if (val < root.val) root = root.left; + else if (val > root.val) root = root.right; + else return root; + return root; + } +} +``` Python: +递归法: + +```python +class Solution: + def searchBST(self, root: TreeNode, val: int) -> TreeNode: + if root is None: + return None + if val < root.val: return self.searchBST(root.left, val) + elif val > root.val: return self.searchBST(root.right, val) + else: return root +``` + +迭代法: + +```python +class Solution: + def searchBST(self, root: TreeNode, val: int) -> TreeNode: + while root is not None: + if val < root.val: root = root.left + elif val > root.val: root = root.right + else: return root + return root +``` + Go: @@ -156,4 +205,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 From ef11a0cfdf318063b6b8f24fbd5bfeea86ef431a Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 20:05:10 +0800 Subject: [PATCH 096/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200027.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 959474fc..55c1a1dc 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -123,6 +123,22 @@ public: Java: +```java +class Solution { + public int removeElement(int[] nums, int val) { + int p2 = 0; + + for (int p1 = 0; p1 < nums.length; p1++) { + if (nums[p1] != val) { + nums[p2] = nums[p1]; + p2++; + } + } + + return p2; + } +} +``` Python: @@ -172,4 +188,4 @@ var removeElement = (nums, val) => { * 作者微信:[程序员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 +
From 248082f741629d49123e3b23b5ea476484b37a3a Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 20:19:24 +0800 Subject: [PATCH 097/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00377.=E7=BB=84?= =?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8C=E2=85=A3=20Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0377.组合总和Ⅳ.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index b0b83718..fbede43d 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -148,9 +148,22 @@ C++测试用例有超过两个树相加超过int的数据,所以需要在if里 Java: - Python: +```python +class Solution: + def combinationSum4(self, nums, target): + dp = [0] * (target + 1) + dp[0] = 1 + + for i in range(1, target+1): + for j in nums: + if i >= j: + dp[i] += dp[i - j] + + return dp[-1] +``` + Go: @@ -161,4 +174,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 From 07c3db6288cd3d423cfe32a7690ecd07179de254 Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 20:21:03 +0800 Subject: [PATCH 098/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200142.=E7=8E=AF?= =?UTF-8?q?=E5=BD=A2=E9=93=BE=E8=A1=A8II.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0142.环形链表II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 9622affc..cd6347ef 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -186,7 +186,35 @@ public: Java: +```java +public class Solution { + public ListNode detectCycle(ListNode head) { + // 1.寻找相遇点 + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (fast != slow) { + continue; + } + ListNode meet = fast; + + // 2.寻找入口点 + slow = head; + while (slow != fast) { + slow = slow.next; + fast = fast.next; + } + + return fast; + } + + return null; + } +} +``` Python: From bb844aa46a5264408791fd30f07e363a454fbfd2 Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 20:44:47 +0800 Subject: [PATCH 099/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200151.=E7=BF=BB?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95?= =?UTF-8?q?=E8=AF=8D.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 71 ++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d81c139d..13938fd9 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -212,6 +212,77 @@ public: Java: +```java +class Solution { + public String reverseWords(String s) { + char[] chars = s.toCharArray(); + // 1.双指针去除空格 + // 去除头尾空格 + int head = 0; + while (chars[head] == ' ') { + head ++; + } + int tail = chars.length - 1; + while (chars[tail] == ' ') { + tail --; + } + + // 去除中间空格 + int p1 = head; + int p2 = head + 1; + while (p2 <= tail) { + if (chars[p2 -1] == ' ' && chars[p2] == ' ') { + p2 ++; + continue; + } + chars[p1 + 1] = chars[p2]; + p1 ++; + p2 ++; + } + + tail = p1; + + // 2.双指针翻转整个字符串 + chars = reverse(chars, head, tail); + + // 3.双指针翻转每个单词 + p1 = head; + p2 = head; + + for (int i = head; i <= tail;) { + int add = 0; + while (i + add <= tail && chars[i + add] != ' ') { + add ++; + } + + if (i + add != tail) { + reverse(chars, i, i + add - 1); + i += add + 1; + } else { + reverse(chars, i, tail); + i = tail + 1; + } + } + + return new String(chars, head, tail - head + 1); + } + + char[] reverse(char[] chars, int begin, int end) { + int p1 = begin; + int p2 = end; + + while (p1 < p2) { + chars[p1] ^= chars[p2]; + chars[p2] ^= chars[p1]; + chars[p1] ^= chars[p2]; + + p1 ++; + p2 --; + } + return chars; + } +} +``` Python: From 11cfcdf1b96045139013acdc4ee15feeee2d8d0b Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 20:52:01 +0800 Subject: [PATCH 100/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200101.=E5=AF=B9?= =?UTF-8?q?=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 89 +++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 535300af..05a67623 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -254,7 +254,94 @@ public: ## 其他语言版本 Java: +```java +public class N0101 { + /** + * 解法1:DFS,递归。 + */ + public boolean isSymmetric2(TreeNode root) { + if (root == null) { + return false; + } + return compare(root.left, root.right); + } + + private boolean compare(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left != null && right == null) { + return false; + } + if (left == null && right != null) { + return false; + } + + if (left.val == right.val) { + return compare(left.left, right.right) && compare(left.right, right.left); + } + + return false; + } + + /** + * 解法2:DFS,迭代 + */ + public boolean isSymmetric3(TreeNode root) { + if (root == null) { + return false; + } + + if (!equal(root.left, root.right)) { + return false; + } + + Deque st = new LinkedList<>(); + + st.push(root.right); + st.push(root.left); + + TreeNode curR = root.right; + TreeNode curL = root.left; + + while (!st.isEmpty()) { + curL = st.pop(); + curR = st.pop(); + + // 前序,处理 + if (!equal(curL, curR)) { + return false; + } + + if (curR != null && curL != null) { + st.push(curL.right); + st.push(curR.left); + st.push(curR.right); + st.push(curL.left); + } + } + + return true; + } + + private boolean equal(TreeNode l, TreeNode r) { + if (l == null && r == null) { + return true; + } + if (l != null && r == null) { + return false; + } + if (l == null && r != null) { + return false; + } + if (l.val == r.val) { + return true; + } + return false; + } +} +``` Python: @@ -283,4 +370,4 @@ const check = (leftPtr, rightPtr) => { * 作者微信:[程序员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 +
From bf7254925ad258cf2e62fa21e577b1c3416bb5cb Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Thu, 13 May 2021 21:24:03 +0800 Subject: [PATCH 101/177] Update --- problems/数组理论基础.md | 159 ++++++++++++++------------------- 1 file changed, 68 insertions(+), 91 deletions(-) diff --git a/problems/数组理论基础.md b/problems/数组理论基础.md index c36cc8f7..f061088f 100644 --- a/problems/数组理论基础.md +++ b/problems/数组理论基础.md @@ -7,6 +7,7 @@

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ ## 数组理论基础 数组是非常基础的数据结构,在面试中,考察数组的题目一般在思维上都不难,主要是考察对代码的掌控能力 @@ -23,6 +24,8 @@ ![算法通关数组](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%84.png) + + 需要两点注意的是 * **数组下标都是从0开始的。** @@ -34,6 +37,7 @@ ![算法通关数组1](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%841.png) + 而且大家如果使用C++的话,要注意vector 和 array的区别,vector的底层实现是array,严格来讲vector是容器,不是数组。 **数组的元素是不能删的,只能覆盖。** @@ -42,106 +46,79 @@ ![算法通关数组2](https://code-thinking.cdn.bcebos.com/pics/%E7%AE%97%E6%B3%95%E9%80%9A%E5%85%B3%E6%95%B0%E7%BB%842.png) + **那么二维数组在内存的空间地址是连续的么?** -不同编程语言的内存管理是不一样的,以C++为例,在C++中二维数组是连续分布的,如图: +不同编程语言的内存管理是不一样的,以C++为例,在C++中二维数组是连续分布的。 + +我们来做一个实验,C++测试代码如下: + +```C++ +void test_arr() { + int array[2][3] = { + {0, 1, 2}, + {3, 4, 5} + }; + cout << &array[0][0] << " " << &array[0][1] << " " << &array[0][2] << endl; + cout << &array[1][0] << " " << &array[1][1] << " " << &array[1][2] << endl; +} + +int main() { + test_arr(); +} + +``` + +测试地址为 + +``` +0x7ffee4065820 0x7ffee4065824 0x7ffee4065828 +0x7ffee406582c 0x7ffee4065830 0x7ffee4065834 +``` + +注意地址为16进制,可以看出二维数组地址是连续一条线的。 + +一些录友可能看不懂内存地址,我就简单介绍一下, 0x7ffee4065820 与 0x7ffee4065824 差了一个4,就是4个字节,因为这是一个int型的数组,所以两个相信数组元素地址差4个字节。 + +0x7ffee4065828 与 0x7ffee406582c 也是差了4个字节,在16进制里8 + 4 = c,c就是12。 + +如图: ![数组内存](https://img-blog.csdnimg.cn/20210310150641186.png) -Java的二维数组可能是如下排列的方式: +**所以可以看出在C++中二维数组在地址空间上是连续的**。 + +像Java是没有指针的,同时也不对程序员暴漏其元素的地址,寻址操作完全交给虚拟机。 + +所以看不到每个元素的地址情况,这里我以Java为例,也做一个实验。 + +```Java +public static void test_arr() { + int[][] arr = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}, {9,9,9}}; + System.out.println(arr[0]); + System.out.println(arr[1]); + System.out.println(arr[2]); + System.out.println(arr[3]); +} +``` +输出的地址为: + +``` +[I@7852e922 +[I@4e25154f +[I@70dea4e +[I@5c647e05 +``` + +这里的数值也是16进制,这不是真正的地址,而是经过处理过后的数值了,我们也可以看出,二维数组的每一行头结点的地址是没有规则的,更谈不上连续。 + +所以Java的二维数组可能是如下排列的方式: ![算法通关数组3](https://img-blog.csdnimg.cn/20201214111631844.png) -我们在[数组过于简单,但你该了解这些!](https://mp.weixin.qq.com/s/c2KABb-Qgg66HrGf8z-8Og)分别作了实验 +这里面试中数组相关的理论知识就介绍完了。 -## 数组的经典题目 - -在面试中,数组是必考的基础数据结构。 - -其实数据的题目在思想上一般比较简单的,但是如果想高效,并不容易。 - -我们之前一共讲解了四道经典数组题目,每一道题目都代表一个类型,一种思想。 - -### 二分法 - -[704.二分查找](https://mp.weixin.qq.com/s/4X-8VRgnYRGd5LYGZ33m4w) - -在这道题目中我们讲到了**循环不变量原则**,只有在循环中坚持对区间的定义,才能清楚的把握循环中的各种细节。 - -**二分法是算法面试中的常考题,建议通过这道题目,锻炼自己手撕二分的能力**。 - -相关题目: - -* 35.搜索插入位置 -* 34.在排序数组中查找元素的第一个和最后一个位置 -* 69.x 的平方根 -* 367.有效的完全平方数 - -### 双指针法 - -[27. 移除元素](https://mp.weixin.qq.com/s/RMkulE4NIb6XsSX83ra-Ww) - -双指针法(快慢指针法):**通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。** - -暴力解法时间复杂度:O(n^2) -双指针时间复杂度:O(n) - -这道题目迷惑了不少同学,纠结于数组中的元素为什么不能删除,主要是因为一下两点: - -* 数组在内存中是连续的地址空间,不能释放单一元素,如果要释放,就是全释放(程序运行结束,回收内存栈空间)。 -* C++中vector和array的区别一定要弄清楚,vector的底层实现是array,所以vector展现出友好的一些都是因为经过包装了。 - -双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组和链表操作的面试题,都使用双指针法。 - -相关题目: - -* 26.删除排序数组中的重复项 -* 283.移动零 -* 844.比较含退格的字符串 -* 977.有序数组的平方 - -### 滑动窗口 - -[209.长度最小的子数组](https://mp.weixin.qq.com/s/ewCRwVw0h0v4uJacYO7htQ) - -本题介绍了数组操作中的另一个重要思想:滑动窗口。 - -暴力解法时间复杂度:O(n^2) -滑动窗口时间复杂度:O(n) - -本题中,主要要理解滑动窗口如何移动 窗口起始位置,达到动态更新窗口大小的,从而得出长度最小的符合条件的长度。 - -**滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)的暴力解法降为O(n)。** - -如果没有接触过这一类的方法,很难想到类似的解题思路,滑动窗口方法还是很巧妙的。 - -相关题目: - -* 904.水果成篮 -* 76.最小覆盖子串 - -### 模拟行为 - -[59.螺旋矩阵II](https://mp.weixin.qq.com/s/Hn6-mlCPvKAdWbiFfQyaaw) - -模拟类的题目在数组中很常见,不涉及到什么算法,就是单纯的模拟,十分考察大家对代码的掌控能力。 - -在这道题目中,我们再一次介绍到了**循环不变量原则**,其实这也是写程序中的重要原则。 - -相信大家又遇到过这种情况: 感觉题目的边界调节超多,一波接着一波的判断,找边界,踩了东墙补西墙,好不容易运行通过了,代码写的十分冗余,毫无章法,其实**真正解决题目的代码都是简洁的,或者有原则性的**,大家可以在这道题目中体会到这一点。 - -相关题目: - -* 54.螺旋矩阵 -* 剑指Offer 29.顺时针打印矩阵 - -## 总结 - -从二分法到双指针,从滑动窗口到螺旋矩阵,相信如果大家真的认真做了「代码随想录」每日推荐的题目,定会有所收获。 - -**每道题目后面都有相关练习题,也别忘了去做做!** - -数组专题中讲解和相关题目已经有16道了,就不介绍太过题目了,因为数组是非常基础的数据结构后面很多专题还会用到数组,所以后面的题目依然会会间接练习数组的。 +后续我将介绍面试中数组相关的五道经典面试题目,敬请期待! ## 其他语言版本 From 0eba147159e610b953226e8e3f2c7f53ad754de8 Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 21:25:03 +0800 Subject: [PATCH 102/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200102.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 228 +++++++++++++++++++--- 1 file changed, 205 insertions(+), 23 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 0781e01d..9b5f9ed5 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -420,54 +420,236 @@ public: Java: ```Java +// 102.二叉树的层序遍历 class Solution { - public List> resList=new ArrayList>(); + public List> resList = new ArrayList>(); + public List> levelOrder(TreeNode root) { //checkFun01(root,0); checkFun02(root); - + return resList; } - //DFS--递归方式 - public void checkFun01(TreeNode node,Integer deep){ - if(node==null) return; + //DFS--递归方式 + public void checkFun01(TreeNode node, Integer deep) { + if (node == null) return; deep++; - if(resList.size() item=new ArrayList(); + List item = new ArrayList(); resList.add(item); } - resList.get(deep-1).add(node.val); - - checkFun01(node.left,deep); - checkFun01(node.right,deep); + resList.get(deep - 1).add(node.val); + + checkFun01(node.left, deep); + checkFun01(node.right, deep); } - + //BFS--迭代方式--借助队列 - public void checkFun02(TreeNode node){ - if(node==null) return; - Queue que=new LinkedList(); + public void checkFun02(TreeNode node) { + if (node == null) return; + Queue que = new LinkedList(); que.offer(node); - while(!que.isEmpty()){ - List itemList=new ArrayList(); - int len=que.size(); + while (!que.isEmpty()) { + List itemList = new ArrayList(); + int len = que.size(); - while(len>0){ - TreeNode tmpNode=que.poll(); + while (len > 0) { + TreeNode tmpNode = que.poll(); itemList.add(tmpNode.val); - if(tmpNode.left!=null) que.offer(tmpNode.left); - if(tmpNode.right!=null) que.offer(tmpNode.right); + if (tmpNode.left != null) que.offer(tmpNode.left); + if (tmpNode.right != null) que.offer(tmpNode.right); len--; } - + resList.add(itemList); } } +} + + +// 107. 二叉树的层序遍历 II +public class N0107 { + + /** + * 解法:队列,迭代。 + * 层序遍历,再翻转数组即可。 + */ + public List> solution1(TreeNode root) { + List> list = new ArrayList<>(); + Deque que = new LinkedList<>(); + + if (root == null) { + return list; + } + + que.offerLast(root); + while (!que.isEmpty()) { + List levelList = new ArrayList<>(); + + int levelSize = que.size(); + for (int i = 0; i < levelSize; i++) { + TreeNode peek = que.peekFirst(); + levelList.add(que.pollFirst().val); + + if (peek.left != null) { + que.offerLast(peek.left); + } + if (peek.right != null) { + que.offerLast(peek.right); + } + } + list.add(levelList); + } + + List> result = new ArrayList<>(); + for (int i = list.size() - 1; i >= 0; i-- ) { + result.add(list.get(i)); + } + + return result; + } +} + +// 199.二叉树的右视图 +public class N0199 { + /** + * 解法:队列,迭代。 + * 每次返回每层的最后一个字段即可。 + * + * 小优化:每层右孩子先入队。代码略。 + */ + public List rightSideView(TreeNode root) { + List list = new ArrayList<>(); + Deque que = new LinkedList<>(); + + if (root == null) { + return list; + } + + que.offerLast(root); + while (!que.isEmpty()) { + int levelSize = que.size(); + + for (int i = 0; i < levelSize; i++) { + TreeNode poll = que.pollFirst(); + + if (poll.left != null) { + que.addLast(poll.left); + } + if (poll.right != null) { + que.addLast(poll.right); + } + + if (i == levelSize - 1) { + list.add(poll.val); + } + } + } + + return list; + } +} + +// 637. 二叉树的层平均值 +public class N0637 { + + /** + * 解法:队列,迭代。 + * 每次返回每层的最后一个字段即可。 + */ + public List averageOfLevels(TreeNode root) { + List list = new ArrayList<>(); + Deque que = new LinkedList<>(); + + if (root == null) { + return list; + } + + que.offerLast(root); + while (!que.isEmpty()) { + TreeNode peek = que.peekFirst(); + + int levelSize = que.size(); + double levelSum = 0.0; + for (int i = 0; i < levelSize; i++) { + TreeNode poll = que.pollFirst(); + + levelSum += poll.val; + + if (poll.left != null) { + que.addLast(poll.left); + } + if (poll.right != null) { + que.addLast(poll.right); + } + } + list.add(levelSum / levelSize); + } + return list; + } +} + +// 429. N 叉树的层序遍历 +public class N0429 { + /** + * 解法1:队列,迭代。 + */ + public List> levelOrder(Node root) { + List> list = new ArrayList<>(); + Deque que = new LinkedList<>(); + + if (root == null) { + return list; + } + + que.offerLast(root); + while (!que.isEmpty()) { + int levelSize = que.size(); + List levelList = new ArrayList<>(); + + for (int i = 0; i < levelSize; i++) { + Node poll = que.pollFirst(); + + levelList.add(poll.val); + + List children = poll.children; + if (children == null || children.size() == 0) { + continue; + } + for (Node child : children) { + if (child != null) { + que.offerLast(child); + } + } + } + list.add(levelList); + } + + return list; + } + + class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } + } +} ``` From 5e26155ea90605897f67b027e03cbc3a3b2b6c81 Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 21:59:23 +0800 Subject: [PATCH 103/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200347.=E5=89=8D=20K?= =?UTF-8?q?=20=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md=20Java?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 1902bd68..9ec601a7 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -133,7 +133,59 @@ public: Java: +```java +public class N0347 { + /** + * 解法: + * 1.统计频次。O(n) + * 2.排序。O(nlogn) + * 3.取前K个元素 + * + * 注意到,排序的时候需要用小顶堆,而不是大顶堆。因为每次需要把最小的堆顶弹出去,最后才剩下最大的k个。 + * 时间复杂度:O(n + nlogk) = O(nlogk) + */ + public int[] topKFrequent(int[] nums, int k) { + HashMap map = statistic(nums); + PriorityQueue pq = new PriorityQueue<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + return map.get(o1) - map.get(o2); + } + }); + + for (Integer key : map.keySet()) { + if (pq.size() < k) { + pq.offer(key); + } else if (map.get(pq.peek()) < map.get(key)){ + pq.poll(); + pq.offer(key); + } + } + + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + result[i] = pq.poll(); + } + return result; + } + + + // key: 值,value:次数 + private HashMap statistic(int[] nums) { + HashMap map = new HashMap<>(); + for (int num : nums) { + if (map.get(num) == null) { + map.put(num, 1); + } else { + map.put(num, map.get(num) + 1); + } + } + + return map; + } +} +``` Python: From 7d9ec4360849d8363d7df07d631f3787f10e21bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=81=92=E6=98=9F=E8=A7=82=E6=B5=8B=E5=91=983400=E5=8F=B7?= <1063934054@qq.com> Date: Thu, 13 May 2021 22:01:48 +0800 Subject: [PATCH 104/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00104.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20JavaScript=E7=89=88=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 814beb55..b7eb8142 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -239,7 +239,13 @@ Python: Go: - +JavaScript +```javascript +var maxDepth = function(root) { + if (!root) return root + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)) +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From cb89178e649eaed3917132fb83848d92eca1dc21 Mon Sep 17 00:00:00 2001 From: hujiale Date: Thu, 13 May 2021 22:26:18 +0800 Subject: [PATCH 105/177] =?UTF-8?q?0516=E6=9C=80=E9=95=BF=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0516.最长回文子序列.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md index 813e75f5..d7acef99 100644 --- a/problems/0516.最长回文子序列.md +++ b/problems/0516.最长回文子序列.md @@ -148,6 +148,25 @@ public: Java: +```java +public class Solution { + public int longestPalindromeSubseq(String s) { + int len = s.length(); + int[][] dp = new int[len + 1][len + 1]; + for (int i = len - 1; i >= 0; i--) { // 从后往前遍历 保证情况不漏 + dp[i][i] = 1; // 初始化 + for (int j = i + 1; j < len; j++) { + if (s.charAt(i) == s.charAt(j)) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i + 1][j], Math.max(dp[i][j], dp[i][j - 1])); + } + } + } + return dp[0][len - 1]; + } +} +``` Python: From 7af428dbe29f3ebfc7ebc11da98eee7e2b981525 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Thu, 13 May 2021 22:45:20 +0800 Subject: [PATCH 106/177] =?UTF-8?q?Update=200209.=E9=95=BF=E5=BA=A6?= =?UTF-8?q?=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0209.长度最小的子数组 Java版本 --- problems/0209.长度最小的子数组.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 1b00c4e3..c4b14d6e 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -148,7 +148,24 @@ class Solution: Java: - +```java +class Solution { + // 滑动窗口 + public int minSubArrayLen(int s, int[] nums) { + int left = 0; + int sum = 0; + int result = Integer.MAX_VALUE; + for (int right = 0; right < nums.length; right++) { + sum += nums[right]; + while (sum >= s) { + result = Math.min(result, right - left + 1); + sum -= nums[left++]; + } + } + return result == Integer.MAX_VALUE ? 0 : result; + } +} +``` Python: From 8589ae546b84ed150d88b31f663c378e47a6ff79 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Thu, 13 May 2021 22:50:47 +0800 Subject: [PATCH 107/177] =?UTF-8?q?Update=200027.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0027.移除元素 Java版本 --- problems/0027.移除元素.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 959474fc..aab174cf 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -123,6 +123,22 @@ public: Java: +```java +class Solution { + public int removeElement(int[] nums, int val) { + // 快慢指针 + int fastIndex = 0; + int slowIndex; + for (slowIndex = 0; fastIndex < nums.length; fastIndex++) { + if (nums[fastIndex] != val) { + nums[slowIndex] = nums[fastIndex]; + slowIndex++; + } + } + return slowIndex; + } +} +``` Python: @@ -172,4 +188,4 @@ var removeElement = (nums, val) => { * 作者微信:[程序员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 +
From cd919ae432cdd9dff853c49e1d62b93e9d4bf5d6 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Thu, 13 May 2021 23:03:45 +0800 Subject: [PATCH 108/177] =?UTF-8?q?Update=200216.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8CIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0216.组合总和III Java版本 --- problems/0216.组合总和III.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 11a8eb8f..38af4c86 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -227,7 +227,38 @@ public: Java: +```java +class Solution { + List> res = new ArrayList<>(); + List list = new ArrayList<>(); + public List> combinationSum3(int k, int n) { + res.clear(); + list.clear(); + backtracking(k, n, 9); + return res; + } + + private void backtracking(int k, int n, int maxNum) { + if (k == 0 && n == 0) { + res.add(new ArrayList<>(list)); + return; + } + + // 因为不能重复,并且单个数字最大值是maxNum,所以sum最大值为 + // (maxNum + (maxNum - 1) + ... + (maxNum - k + 1)) == k * maxNum - k*(k - 1) / 2 + if (maxNum == 0 + || n > k * maxNum - k * (k - 1) / 2 + || n < (1 + k) * k / 2) { + return; + } + list.add(maxNum); + backtracking(k - 1, n - maxNum, maxNum - 1); + list.remove(list.size() - 1); + backtracking(k, n, maxNum - 1); + } +} +``` Python: From 3e40ed234765bb7ae5cf6c769458a5c96be54579 Mon Sep 17 00:00:00 2001 From: phoenix Date: Thu, 13 May 2021 23:06:42 +0800 Subject: [PATCH 109/177] =?UTF-8?q?0020.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E6=8B=AC=E5=8F=B7=20+=20ruby=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 9f6c8487..77c6e10a 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -202,6 +202,23 @@ func isValid(s string) bool { } ``` +Ruby: +```ruby +def is_valid(strs) + symbol_map = {')' => '(', '}' => '{', ']' => '['} + stack = [] + strs.size.times {|i| + c = strs[i] + if symbol_map.has_key?(c) + top_e = stack.shift + return false if symbol_map[c] != top_e + else + stack.unshift(c) + end + } + stack.empty? +end +``` ----------------------- From d850713638583fe3aab28ddd71495f12959883a4 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Thu, 13 May 2021 23:17:10 +0800 Subject: [PATCH 110/177] =?UTF-8?q?Update=200142.=E7=8E=AF=E5=BD=A2?= =?UTF-8?q?=E9=93=BE=E8=A1=A8II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0142.环形链表II.md Java版本 --- problems/0142.环形链表II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 9622affc..7556b854 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -186,6 +186,29 @@ public: Java: +```java +public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (slow == fast) {// 有环 + ListNode index1 = fast; + ListNode index2 = head; + // 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口 + while (index1 != index2) { + index1 = index1.next; + index2 = index2.next; + } + return index1; + } + } + return null; + } +} +``` Python: From 5b6d47dba9b09504f7b5effaab79e7d4ecfa40f0 Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Thu, 13 May 2021 23:27:38 +0800 Subject: [PATCH 111/177] =?UTF-8?q?Update=200122.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0122.买卖股票的最佳时机II.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 1a9b4f7f..61954ce2 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -138,7 +138,14 @@ Java: Python: - +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + result = 0 + for i in range(1, len(prices)): + result += max(prices[i] - prices[i - 1], 0) + return result +``` Go: From a82c6d230dc4d3acae610e0515e9dff70b3ad034 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Thu, 13 May 2021 23:56:10 +0800 Subject: [PATCH 112/177] =?UTF-8?q?Update=200206.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E9=93=BE=E8=A1=A8.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0206.翻转链表 Java版本 --- problems/0206.翻转链表.md | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index b465cdf9..e132fb0d 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -102,7 +102,47 @@ public: Java: +```java +class Solution { + // 双指针 + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode cur = head; + ListNode temp = null; + while (cur != null) { + temp = cur.next;// 保存下一个节点 + cur.next = prev; + prev = cur; + cur = temp; + } + return prev; + } +} +``` +```java +class Solution { + /** + * 递归 + */ + public ListNode reverseList(ListNode head) { + return reverse(null, head); + } + + private ListNode reverse(ListNode prev, ListNode cur) { + if (cur == null) { + return prev; + } + ListNode temp = null; + temp = cur.next;// 先保存下一个节点 + cur.next = prev;// 反转 + // 更新prev、cur位置 + prev = cur; + cur = temp; + return reverse(prev, cur); + } +} +``` Python: From cda8a521b6066e2eaacc51c8919664389cd8612e Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:01:52 +0800 Subject: [PATCH 113/177] =?UTF-8?q?Update=200347.=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0347.前K个高频元素 Java版本 --- problems/0347.前K个高频元素.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 1902bd68..6e94a6ea 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -133,7 +133,31 @@ public: Java: +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + int[] result = new int[k]; + HashMap map = new HashMap<>(); + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + Set> entries = map.entrySet(); + // 根据map的value值正序排,相当于一个小顶堆 + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + for (Map.Entry entry : entries) { + queue.offer(entry); + if (queue.size() > k) { + queue.poll(); + } + } + for (int i = k - 1; i >= 0; i--) { + result[i] = queue.poll().getKey(); + } + return result; + } +} +``` Python: From c80f574f5ca5fb7061af470f4da0412c353d681b Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Fri, 14 May 2021 00:10:35 +0800 Subject: [PATCH 114/177] =?UTF-8?q?Update=200055.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0055.跳跃游戏.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 0cad1fa7..5454273e 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -89,7 +89,19 @@ Java: Python: - +```python +class Solution: + def canJump(self, nums: List[int]) -> bool: + cover = 0 + if len(nums) == 1: return True + i = 0 + # python不支持动态修改for循环中变量,使用while循环代替 + while i <= cover: + cover = max(i + nums[i], cover) + if cover >= len(nums) - 1: return True + i += 1 + return False +``` Go: From 360308ee8a4b1789f856fc1a0ca7b877e20f8579 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:27:24 +0800 Subject: [PATCH 115/177] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0151.翻转字符串里的单词 Java版本 --- problems/0151.翻转字符串里的单词.md | 67 ++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d81c139d..dc3c515c 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -212,7 +212,74 @@ public: Java: +```Java +class Solution { + /** + * 不使用Java内置方法实现 + *

+ * 1.去除首尾以及中间多余空格 + * 2.反转整个字符串 + * 3.反转各个单词 + */ + public String reverseWords(String s) { + // System.out.println("ReverseWords.reverseWords2() called with: s = [" + s + "]"); + // 1.去除首尾以及中间多余空格 + StringBuilder sb = removeSpace(s); + // 2.反转整个字符串 + reverseString(sb, 0, sb.length() - 1); + // 3.反转各个单词 + reverseEachWord(sb); + return sb.toString(); + } + private StringBuilder removeSpace(String s) { + // System.out.println("ReverseWords.removeSpace() called with: s = [" + s + "]"); + int start = 0; + int end = s.length() - 1; + while (s.charAt(start) == ' ') start++; + while (s.charAt(end) == ' ') end--; + StringBuilder sb = new StringBuilder(); + while (start <= end) { + char c = s.charAt(start); + if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') { + sb.append(c); + } + start++; + } + // System.out.println("ReverseWords.removeSpace returned: sb = [" + sb + "]"); + return sb; + } + + /** + * 反转字符串指定区间[start, end]的字符 + */ + public void reverseString(StringBuilder sb, int start, int end) { + // System.out.println("ReverseWords.reverseString() called with: sb = [" + sb + "], start = [" + start + "], end = [" + end + "]"); + while (start < end) { + char temp = sb.charAt(start); + sb.setCharAt(start, sb.charAt(end)); + sb.setCharAt(end, temp); + start++; + end--; + } + // System.out.println("ReverseWords.reverseString returned: sb = [" + sb + "]"); + } + + private void reverseEachWord(StringBuilder sb) { + int start = 0; + int end = 1; + int n = sb.length(); + while (start < n) { + while (end < n && sb.charAt(end) != ' ') { + end++; + } + reverseString(sb, start, end - 1); + start = end + 1; + end = start + 1; + } + } +} +``` Python: From a2743f2442c60c95b7aed7591053578d22ccb57a Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:38:29 +0800 Subject: [PATCH 116/177] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.?= =?UTF-8?q?md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0028.实现strStr Java版本,基于滑动窗口的算法 --- problems/0028.实现strStr.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index f1de00f8..c6463e8b 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -565,6 +565,54 @@ public: Java: +```Java +class Solution { + /** + * 基于窗口滑动的算法 + *

+ * 时间复杂度:O(m*n) + * 空间复杂度:O(1) + * 注:n为haystack的长度,m为needle的长度 + */ + public int strStr(String haystack, String needle) { + int m = needle.length(); + // 当 needle 是空字符串时我们应当返回 0 + if (m == 0) { + return 0; + } + int n = haystack.length(); + if (n < m) { + return -1; + } + int i = 0; + int j = 0; + while (i < n - m + 1) { + // 找到首字母相等 + while (i < n && haystack.charAt(i) != needle.charAt(j)) { + i++; + } + if (i == n) {// 没有首字母相等的 + return -1; + } + // 遍历后续字符,判断是否相等 + i++; + j++; + while (i < n && j < m && haystack.charAt(i) == needle.charAt(j)) { + i++; + j++; + } + if (j == m) {// 找到 + return i - j; + } else {// 未找到 + i -= j - 1; + j = 0; + } + } + return -1; + } +} +``` + ```java // 方法一 class Solution { From f8994be2d2f46972acfb986000630ddebe633a25 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:51:13 +0800 Subject: [PATCH 117/177] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0110.平衡二叉树 Java版本,3种解法 --- problems/0110.平衡二叉树.md | 141 ++++++++++++++++++++++++++++++- 1 file changed, 140 insertions(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index ac66cc40..11c31fc9 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -354,7 +354,146 @@ public: ## 其他语言版本 Java: +```Java +class Solution { + /** + * 递归法 + */ + public boolean isBalanced(TreeNode root) { + return getHeight(root) != -1; + } + private int getHeight(TreeNode root) { + if (root == null) { + return 0; + } + int leftHeight = getHeight(root.left); + if (leftHeight == -1) { + return -1; + } + int rightHeight = getHeight(root.right); + if (rightHeight == -1) { + return -1; + } + // 左右子树高度差大于1,return -1表示已经不是平衡树了 + if (Math.abs(leftHeight - rightHeight) > 1) { + return -1; + } + return Math.max(leftHeight, rightHeight) + 1; + } +} + +class Solution { + /** + * 迭代法,效率较低,计算高度时会重复遍历 + * 时间复杂度:O(n^2) + */ + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + Stack stack = new Stack<>(); + TreeNode pre = null; + while (root!= null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + TreeNode inNode = stack.peek(); + // 右结点为null或已经遍历过 + if (inNode.right == null || inNode.right == pre) { + // 比较左右子树的高度差,输出 + if (Math.abs(getHeight(inNode.left) - getHeight(inNode.right)) > 1) { + return false; + } + stack.pop(); + pre = inNode; + root = null;// 当前结点下,没有要遍历的结点了 + } else { + root = inNode.right;// 右结点还没遍历,遍历右结点 + } + } + return true; + } + + /** + * 层序遍历,求结点的高度 + */ + public int getHeight(TreeNode root) { + if (root == null) { + return 0; + } + Deque deque = new LinkedList<>(); + deque.offer(root); + int depth = 0; + while (!deque.isEmpty()) { + int size = deque.size(); + depth++; + for (int i = 0; i < size; i++) { + TreeNode poll = deque.poll(); + if (poll.left != null) { + deque.offer(poll.left); + } + if (poll.right != null) { + deque.offer(poll.right); + } + } + } + return depth; + } +} + +class Solution { + /** + * 优化迭代法,针对暴力迭代法的getHeight方法做优化,利用TreeNode.val来保存当前结点的高度,这样就不会有重复遍历 + * 获取高度算法时间复杂度可以降到O(1),总的时间复杂度降为O(n)。 + *

+ * 时间复杂度:O(n) + */ + public boolean isBalanced(TreeNode root) { + if (root == null) { + return true; + } + Stack stack = new Stack<>(); + TreeNode pre = null; + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left; + } + TreeNode inNode = stack.peek(); + // 右结点为null或已经遍历过 + if (inNode.right == null || inNode.right == pre) { + // 输出 + if (Math.abs(getHeight(inNode.left) - getHeight(inNode.right)) > 1) { + return false; + } + stack.pop(); + pre = inNode; + root = null;// 当前结点下,没有要遍历的结点了 + } else { + root = inNode.right;// 右结点还没遍历,遍历右结点 + } + } + return true; + } + + /** + * 求结点的高度 + */ + public int getHeight(TreeNode root) { + if (root == null) { + return 0; + } + int leftHeight = root.left != null ? root.left.val : 0; + int rightHeight = root.right != null ? root.right.val : 0; + int height = Math.max(leftHeight, rightHeight) + 1; + root.val = height;// 用TreeNode.val来保存当前结点的高度 + return height; + } +} +LeetCode题解链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/110-ping-heng-er-cha-shu-di-gui-fa-bao-l-yqr3/ +``` Python: @@ -401,4 +540,4 @@ func abs(a int)int{ * 作者微信:[程序员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 +
From 82250d1fc947502b277fe04aebd059b62d05c607 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:54:12 +0800 Subject: [PATCH 118/177] =?UTF-8?q?Update=200257.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0257.二叉树的所有路径 Java版本 --- problems/0257.二叉树的所有路径.md | 40 +++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index a104b27c..c0746260 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -282,7 +282,47 @@ public: Java: +```Java +class Solution { + /** + * 递归法 + */ + public List binaryTreePaths(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) { + return res; + } + List paths = new ArrayList<>(); + traversal(root, paths, res); + return res; + } + private void traversal(TreeNode root, List paths, List res) { + paths.add(root.val); + // 叶子结点 + if (root.left == null && root.right == null) { + // 输出 + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < paths.size() - 1; i++) { + sb.append(paths.get(i)).append("->"); + + } + sb.append(paths.get(paths.size() - 1)); + res.add(sb.toString()); + return; + } + if (root.left != null) { + traversal(root.left, paths, res); + paths.remove(paths.size() - 1);// 回溯 + } + if (root.right != null) { + traversal(root.right, paths, res); + paths.remove(paths.size() - 1);// 回溯 + } + } +} + +``` Python: From a0e346b02282ac515b8c453abce795eff2189519 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:56:39 +0800 Subject: [PATCH 119/177] =?UTF-8?q?Update=200106.=E4=BB=8E=E4=B8=AD?= =?UTF-8?q?=E5=BA=8F=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0106.从中序与后序遍历序列构造二叉树 Java版本 --- ...序与后序遍历序列构造二叉树.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index f1f30b71..5533a818 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -582,7 +582,41 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 Java: +```java +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + return buildTree1(inorder, 0, inorder.length, postorder, 0, postorder.length); + } + public TreeNode buildTree1(int[] inorder, int inLeft, int inRight, + int[] postorder, int postLeft, int postRight) { + // 没有元素了 + if (inRight - inLeft < 1) { + return null; + } + // 只有一个元素了 + if (inRight - inLeft == 1) { + return new TreeNode(inorder[inLeft]); + } + // 后序数组postorder里最后一个即为根结点 + int rootVal = postorder[postRight - 1]; + TreeNode root = new TreeNode(rootVal); + int rootIndex = 0; + // 根据根结点的值找到该值在中序数组inorder里的位置 + for (int i = inLeft; i < inRight; i++) { + if (inorder[i] == rootVal) { + rootIndex = i; + } + } + // 根据rootIndex划分左右子树 + root.left = buildTree1(inorder, inLeft, rootIndex, + postorder, postLeft, postLeft + (rootIndex - inLeft)); + root.right = buildTree1(inorder, rootIndex + 1, inRight, + postorder, postLeft + (rootIndex - inLeft), postRight - 1); + return root; + } +} +``` Python: From b35688b7808bad269c2ef75e1b57f1a1fbe7e919 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:59:49 +0800 Subject: [PATCH 120/177] =?UTF-8?q?Update=200538.=E6=8A=8A=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC=E6=8D=A2=E4=B8=BA?= =?UTF-8?q?=E7=B4=AF=E5=8A=A0=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0538.把二叉搜索树转换为累加树 Java版本 --- ...38.把二叉搜索树转换为累加树.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index a5f4c43c..e69b0d46 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -173,7 +173,27 @@ public: Java: +```Java +class Solution { + int sum; + public TreeNode convertBST(TreeNode root) { + sum = 0; + convertBST1(root); + return root; + } + // 按右中左顺序遍历,累加即可 + public void convertBST1(TreeNode root) { + if (root == null) { + return; + } + convertBST1(root.right); + sum += root.val; + root.val = sum; + convertBST1(root.left); + } +} +``` Python: From f856bcfef005fc54d2e55d3e811731ce0f35257b Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:02:55 +0800 Subject: [PATCH 121/177] =?UTF-8?q?Update=200222.=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA?= =?UTF-8?q?=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0222.完全二叉树的节点个数 Java版本,2种解法 --- .../0222.完全二叉树的节点个数.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 367fa717..64705ed6 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -194,7 +194,49 @@ public: Java: +```java +class Solution { + // 通用递归解法 + public int countNodes(TreeNode root) { + if(root == null) { + return 0; + } + return countNodes(root.left) + countNodes(root.right) + 1; + } +} +``` +```java +class Solution { + /** + * 针对完全二叉树的解法 + * + * 满二叉树的结点数为:2^depth - 1 + */ + public int countNodes(TreeNode root) { + if(root == null) { + return 0; + } + int leftDepth = getDepth(root.left); + int rightDepth = getDepth(root.right); + if (leftDepth == rightDepth) {// 左子树是满二叉树 + // 2^leftDepth其实是 (2^leftDepth - 1) + 1 ,左子树 + 根结点 + return (1 << leftDepth) + countNodes(root.right); + } else {// 右子树是满二叉树 + return (1 << rightDepth) + countNodes(root.left); + } + } + + private int getDepth(TreeNode root) { + int depth = 0; + while (root != null) { + root = root.left; + depth++; + } + return depth; + } +} +``` Python: From 7398c373578922cf68c1eb2b6b04b43b55641196 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:04:41 +0800 Subject: [PATCH 122/177] =?UTF-8?q?Update=200513.=E6=89=BE=E6=A0=91?= =?UTF-8?q?=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0513.找树左下角的值 Java版本 --- problems/0513.找树左下角的值.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 19c870c3..538b335f 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -217,7 +217,31 @@ public: Java: - +```java +class Solution { + public int findBottomLeftValue(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.offer(root); + int res = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + TreeNode poll = queue.poll(); + if (i == 0) { + res = poll.val; + } + if (poll.left != null) { + queue.offer(poll.left); + } + if (poll.right != null) { + queue.offer(poll.right); + } + } + } + return res; + } +} +``` Python: From 5f5a4e7fbd21d6aec3fb8fefd3f4734ee958e1c5 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:07:35 +0800 Subject: [PATCH 123/177] =?UTF-8?q?Update=200501.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0501.二叉搜索树中的众数 Java版本 --- problems/0501.二叉搜索树中的众数.md | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 0e8c0d0e..0b2b1bb5 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -344,7 +344,53 @@ public: Java: +```Java +class Solution { + ArrayList resList; + int maxCount; + int count; + TreeNode pre; + public int[] findMode(TreeNode root) { + resList = new ArrayList<>(); + maxCount = 0; + count = 0; + pre = null; + findMode1(root); + int[] res = new int[resList.size()]; + for (int i = 0; i < resList.size(); i++) { + res[i] = resList.get(i); + } + return res; + } + + public void findMode1(TreeNode root) { + if (root == null) { + return; + } + findMode1(root.left); + + int rootValue = root.val; + // 计数 + if (pre == null || rootValue != pre.val) { + count = 1; + } else { + count++; + } + // 更新结果以及maxCount + if (count > maxCount) { + resList.clear(); + resList.add(rootValue); + maxCount = count; + } else if (count == maxCount) { + resList.add(rootValue); + } + pre = root; + + findMode1(root.right); + } +} +``` Python: From 3efcaa6dfcd14ab809f85dec7220429a38f9db58 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:09:44 +0800 Subject: [PATCH 124/177] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0226.翻转二叉树.md Java版本 --- problems/0226.翻转二叉树.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index f5626ea0..dc29a965 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -203,7 +203,29 @@ public: Java: +```Java +class Solution { + /** + * 前后序遍历都可以 + * 中序不行,因为先左孩子交换孩子,再根交换孩子(做完后,右孩子已经变成了原来的左孩子),再右孩子交换孩子(此时其实是对原来的左孩子做交换) + */ + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + invertTree(root.left); + invertTree(root.right); + swapChildren(root); + return root; + } + private void swapChildren(TreeNode root) { + TreeNode tmp = root.left; + root.left = root.right; + root.right = tmp; + } +} +``` Python: From 7fb67acf9a539e94861f9aa4521b0486bfc87c40 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:12:18 +0800 Subject: [PATCH 125/177] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0236.二叉树的最近公共祖先 Java版本 --- .../0236.二叉树的最近公共祖先.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 17096d48..2908c5bb 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -223,7 +223,28 @@ public: Java: +```Java +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + return lowestCommonAncestor1(root, p, q); + } + public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) { + return root; + } + TreeNode left = lowestCommonAncestor1(root.left, p, q); + TreeNode right = lowestCommonAncestor1(root.right, p, q); + if (left != null && right != null) {// 左右子树分别找到了,说明此时的root就是要求的结果 + return root; + } + if (left == null) { + return right; + } + return left; + } +} +``` Python: From 001a4dc00f2441fdd8ed70bdd3304c022d6bfc85 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:12:21 +0800 Subject: [PATCH 126/177] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0236.二叉树的最近公共祖先 Java版本 --- .../0236.二叉树的最近公共祖先.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 17096d48..2908c5bb 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -223,7 +223,28 @@ public: Java: +```Java +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + return lowestCommonAncestor1(root, p, q); + } + public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) { + return root; + } + TreeNode left = lowestCommonAncestor1(root.left, p, q); + TreeNode right = lowestCommonAncestor1(root.right, p, q); + if (left != null && right != null) {// 左右子树分别找到了,说明此时的root就是要求的结果 + return root; + } + if (left == null) { + return right; + } + return left; + } +} +``` Python: From e2b2478559ecb27dbb9db8290cbafd34fe736e2e Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:15:06 +0800 Subject: [PATCH 127/177] =?UTF-8?q?Update=200104.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0104.二叉树的最大深度 Java版本 --- problems/0104.二叉树的最大深度.md | 44 +++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 814beb55..0d3cd693 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -231,7 +231,51 @@ public: Java: +```Java +class Solution { + /** + * 递归法 + */ + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + int leftDepth = maxDepth(root.left); + int rightDepth = maxDepth(root.right); + return Math.max(leftDepth, rightDepth) + 1; + } +} +``` +```Java +class Solution { + /** + * 迭代法,使用层序遍历 + */ + public int maxDepth(TreeNode root) { + if(root == null) { + return 0; + } + Deque deque = new LinkedList<>(); + deque.offer(root); + int depth = 0; + while (!deque.isEmpty()) { + int size = deque.size(); + depth++; + for (int i = 0; i < size; i++) { + TreeNode poll = deque.poll(); + if (poll.left != null) { + deque.offer(poll.left); + } + if (poll.right != null) { + deque.offer(poll.right); + } + } + } + return depth; + } +} +``` Python: From b5abd14fa1110d6c9883de8817a3ae16ccd77b87 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:16:51 +0800 Subject: [PATCH 128/177] =?UTF-8?q?Update=200654.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0654.最大二叉树 Java版本 --- problems/0654.最大二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index af133e0c..83981728 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -224,7 +224,35 @@ root->right = traversal(nums, maxValueIndex + 1, right); Java: +```Java +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + return constructMaximumBinaryTree1(nums, 0, nums.length); + } + public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) { + if (rightIndex - leftIndex < 1) {// 没有元素了 + return null; + } + if (rightIndex - leftIndex == 1) {// 只有一个元素 + return new TreeNode(nums[leftIndex]); + } + int maxIndex = leftIndex;// 最大值所在位置 + int maxVal = nums[maxIndex];// 最大值 + for (int i = leftIndex + 1; i < rightIndex; i++) { + if (nums[i] > maxVal){ + maxVal = nums[i]; + maxIndex = i; + } + } + TreeNode root = new TreeNode(maxVal); + // 根据maxIndex划分左右子树 + root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex); + root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex); + return root; + } +} +``` Python: From 1dd57ca07df04e6d9af8ec4067447651d9433de9 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:19:18 +0800 Subject: [PATCH 129/177] =?UTF-8?q?Update=200617.=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0617.合并二叉树 Java版本 --- problems/0617.合并二叉树.md | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index adc0703b..520a7384 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -256,7 +256,60 @@ public: Java: +```Java +class Solution { + // 递归 + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + root1.val += root2.val; + root1.left = mergeTrees(root1.left, root2.left); + root1.right = mergeTrees(root1.right, root2.right); + return root1; + } +} +class Solution { + // 迭代 + public TreeNode mergeTrees(TreeNode root1, TreeNode root2) { + if (root1 == null) { + return root2; + } + if (root2 == null) { + return root1; + } + Stack stack = new Stack<>(); + stack.push(root2); + stack.push(root1); + while (!stack.isEmpty()) { + TreeNode node1 = stack.pop(); + TreeNode node2 = stack.pop(); + node1.val += node2.val; + if (node2.right != null && node1.right != null) { + stack.push(node2.right); + stack.push(node1.right); + } else { + if (node1.right == null) { + node1.right = node2.right; + } + } + if (node2.left != null && node1.left != null) { + stack.push(node2.left); + stack.push(node1.left); + } else { + if (node1.left == null) { + node1.left = node2.left; + } + } + } + return root1; + } +} +``` Python: From 530de05b69e4b47f3690470f08060824729c8a90 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:21:36 +0800 Subject: [PATCH 130/177] =?UTF-8?q?Update=200111.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0111.二叉树的最小深度 Java版本 --- problems/0111.二叉树的最小深度.md | 57 ++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 6c6b4632..21cf36df 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -194,6 +194,61 @@ public: Java: +```Java +class Solution { + /** + * 递归法,相比求MaxDepth要复杂点 + * 因为最小深度是从根节点到最近**叶子节点**的最短路径上的节点数量 + */ + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } + int leftDepth = minDepth(root.left); + int rightDepth = minDepth(root.right); + if (root.left == null) { + return rightDepth + 1; + } + if (root.right == null) { + return leftDepth + 1; + } + // 左右结点都不为null + return Math.min(leftDepth, rightDepth) + 1; + } +} + +class Solution { + /** + * 迭代法,层序遍历 + */ + public int minDepth(TreeNode root) { + if (root == null) { + return 0; + } + Deque deque = new LinkedList<>(); + deque.offer(root); + int depth = 0; + while (!deque.isEmpty()) { + int size = deque.size(); + depth++; + for (int i = 0; i < size; i++) { + TreeNode poll = deque.poll(); + if (poll.left == null && poll.right == null) { + // 是叶子结点,直接返回depth,因为从上往下遍历,所以该值就是最小值 + return depth; + } + if (poll.left != null) { + deque.offer(poll.left); + } + if (poll.right != null) { + deque.offer(poll.right); + } + } + } + return depth; + } +} +``` Python: @@ -250,4 +305,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 +
From b0bddae257bdb2b7acc580ed23f45f8d2a1a3adc Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:24:15 +0800 Subject: [PATCH 131/177] =?UTF-8?q?Update=200530.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E7=BB=9D?= =?UTF-8?q?=E5=AF=B9=E5=B7=AE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0530.二叉搜索树的最小绝对差 Java版本 --- .../0530.二叉搜索树的最小绝对差.md | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index d5abc692..e30e76f5 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -151,7 +151,29 @@ public: Java: - +```Java +class Solution { + TreeNode pre;// 记录上一个遍历的结点 + int result = Integer.MAX_VALUE; + public int getMinimumDifference(TreeNode root) { + if (root == null) { + return result; + } + // 左 + int left = getMinimumDifference(root.left); + + // 中 + if (pre != null) { + result = Math.min(left, root.val - pre.val); + } + pre = root; + // 右 + int right = getMinimumDifference(root.right); + result = Math.min(right, result); + return result; + } +} +``` Python: From a297f2eab6826ad2dd81feacaa4bb39234fd0684 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:25:56 +0800 Subject: [PATCH 132/177] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=80=BB=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0112.路径总和 Java版本 --- problems/0112.路径总和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 718a2f5b..41d8b802 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -305,7 +305,34 @@ public: Java: +```Java +class Solution { + public boolean hasPathSum(TreeNode root, int targetSum) { + if (root == null) { + return false; + } + targetSum -= root.val; + // 叶子结点 + if (root.left == null && root.right == null) { + return targetSum == 0; + } + if (root.left != null) { + boolean left = hasPathSum(root.left, targetSum); + if (left) {// 已经找到 + return true; + } + } + if (root.right != null) { + boolean right = hasPathSum(root.right, targetSum); + if (right) {// 已经找到 + return true; + } + } + return false; + } +} +``` Python: From 55cbb97ab6983185ebe00c1387333501c6eb70a7 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:31:15 +0800 Subject: [PATCH 133/177] =?UTF-8?q?Update=200700.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C=E7=B4=A2?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0700.二叉搜索树中的搜索 Java版本,4种解法 --- problems/0700.二叉搜索树中的搜索.md | 71 ++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 5c1cdfdf..401c85d5 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -142,7 +142,78 @@ public: Java: +```Java +class Solution { + // 递归 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + TreeNode left = searchBST(root.left, val); + if (left != null) { + return left; + } + return searchBST(root.right, val); + } +} +class Solution { + // 递归,利用二叉搜索树特点,优化 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + if (val < root.val) { + return searchBST(root.left, val); + } else { + return searchBST(root.right, val); + } + } +} + +class Solution { + // 迭代 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + Stack stack = new Stack<>(); + stack.push(root); + while (!stack.isEmpty()) { + TreeNode pop = stack.pop(); + if (pop.val == val) { + return pop; + } + if (pop.right != null) { + stack.push(pop.right); + } + if (pop.left != null) { + stack.push(pop.left); + } + } + return null; + } +} + +class Solution { + // 迭代,利用二叉搜索树特点,优化,可以不需要栈 + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + while (root != null) { + if (root.val == val) { + return root; + } else if (val < root.val) { + root = root.left; + } else { + root = root.right; + } + } + return null; + } +} +``` Python: From aba00b1d5676380f24e924eb1dea270ed17c2355 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:32:46 +0800 Subject: [PATCH 134/177] =?UTF-8?q?Update=200108.=E5=B0=86=E6=9C=89?= =?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E8=BD=AC=E6=8D=A2=E4=B8=BA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0108.将有序数组转换为二叉搜索树 Java版本 --- ...将有序数组转换为二叉搜索树.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 12d47e6a..f3feaf7d 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -209,7 +209,28 @@ public: Java: +```Java +class Solution { + public TreeNode sortedArrayToBST(int[] nums) { + return sortedArrayToBST(nums, 0, nums.length); + } + + public TreeNode sortedArrayToBST(int[] nums, int left, int right) { + if (left >= right) { + return null; + } + if (right - left == 1) { + return new TreeNode(nums[left]); + } + int mid = left + (right - left) / 2; + TreeNode root = new TreeNode(nums[mid]); + root.left = sortedArrayToBST(nums, left, mid); + root.right = sortedArrayToBST(nums, mid + 1, right); + return root; + } +} +``` Python: From 9cf58adff3807e00894bc171fe173c923e18c78c Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:35:48 +0800 Subject: [PATCH 135/177] =?UTF-8?q?Update=200101.=E5=AF=B9=E7=A7=B0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0101.对称二叉树 Java版本,3种解法 --- problems/0101.对称二叉树.md | 100 ++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 535300af..fdb0a929 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -254,7 +254,105 @@ public: ## 其他语言版本 Java: +```Java + /** + * 递归法 + */ + public boolean isSymmetric1(TreeNode root) { + return compare(root.left, root.right); + } + private boolean compare(TreeNode left, TreeNode right) { + if (left == null && right != null) { + return false; + } + if (left != null && right == null) { + return false; + } + if (left == null && right == null) { + return true; + } + if (left.val != right.val) { + return false; + } + // 比较外侧 + boolean compareOutside = compare(left.left, right.right); + // 比较内侧 + boolean compareInside = compare(left.right, right.left); + return compareOutside && compareInside; + } + + /** + * 迭代法 + * 使用双端队列,相当于两个栈 + */ + public boolean isSymmetric2(TreeNode root) { + Deque deque = new LinkedList<>(); + deque.offerFirst(root.left); + deque.offerLast(root.right); + while (!deque.isEmpty()) { + TreeNode leftNode = deque.pollFirst(); + TreeNode rightNode = deque.pollLast(); + if (leftNode == null && rightNode == null) { + continue; + } +// if (leftNode == null && rightNode != null) { +// return false; +// } +// if (leftNode != null && rightNode == null) { +// return false; +// } +// if (leftNode.val != rightNode.val) { +// return false; +// } + // 以上三个判断条件合并 + if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) { + return false; + } + deque.offerFirst(leftNode.left); + deque.offerFirst(leftNode.right); + deque.offerLast(rightNode.right); + deque.offerLast(rightNode.left); + } + return true; + } + + /** + * 迭代法 + * 使用普通队列 + */ + public boolean isSymmetric3(TreeNode root) { + Queue deque = new LinkedList<>(); + deque.offer(root.left); + deque.offer(root.right); + while (!deque.isEmpty()) { + TreeNode leftNode = deque.poll(); + TreeNode rightNode = deque.poll(); + if (leftNode == null && rightNode == null) { + continue; + } +// if (leftNode == null && rightNode != null) { +// return false; +// } +// if (leftNode != null && rightNode == null) { +// return false; +// } +// if (leftNode.val != rightNode.val) { +// return false; +// } + // 以上三个判断条件合并 + if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) { + return false; + } + // 这里顺序与使用Deque不同 + deque.offer(leftNode.left); + deque.offer(rightNode.right); + deque.offer(leftNode.right); + deque.offer(rightNode.left); + } + return true; + } +``` Python: @@ -283,4 +381,4 @@ const check = (leftPtr, rightPtr) => { * 作者微信:[程序员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 +
From 2ae387c45c1a894733ca60e135dff58a58e938f9 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:37:09 +0800 Subject: [PATCH 136/177] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0669.修剪二叉搜索树 Java版本 --- problems/0669.修剪二叉搜索树.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 41f684f4..cf1239c1 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -242,7 +242,25 @@ public: Java: - +```Java +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + if (root == null) { + return null; + } + if (root.val < low) { + return trimBST(root.right, low, high); + } + if (root.val > high) { + return trimBST(root.left, low, high); + } + // root在[low,high]范围内 + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; + } +} +``` Python: From f307e8ec753fc4d612d179d82f14e62988cb73e7 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:37:11 +0800 Subject: [PATCH 137/177] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0669.修剪二叉搜索树 Java版本 --- problems/0669.修剪二叉搜索树.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 41f684f4..cf1239c1 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -242,7 +242,25 @@ public: Java: - +```Java +class Solution { + public TreeNode trimBST(TreeNode root, int low, int high) { + if (root == null) { + return null; + } + if (root.val < low) { + return trimBST(root.right, low, high); + } + if (root.val > high) { + return trimBST(root.left, low, high); + } + // root在[low,high]范围内 + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; + } +} +``` Python: From d68afe722bf2f967d10c4d2ba0676a0d14ab6833 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:38:44 +0800 Subject: [PATCH 138/177] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0098.验证二叉搜索树 Java版本 --- problems/0098.验证二叉搜索树.md | 49 ++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index ddd634b4..336cc92f 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -254,7 +254,56 @@ public: Java: +```Java +class Solution { + // 递归 + TreeNode max; + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + // 左 + boolean left = isValidBST(root.left); + if (!left) { + return false; + } + // 中 + if (max != null && root.val <= max.val) { + return false; + } + max = root; + // 右 + boolean right = isValidBST(root.right); + return right; + } +} +class Solution { + // 迭代 + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + Stack stack = new Stack<>(); + TreeNode pre = null; + while (root != null || !stack.isEmpty()) { + while (root != null) { + stack.push(root); + root = root.left;// 左 + } + // 中,处理 + TreeNode pop = stack.pop(); + if (pre != null && pop.val <= pre.val) { + return false; + } + pre = pop; + + root = pop.right;// 右 + } + return true; + } +} +``` Python: From 8e79c69a8575a6419c13d5a28cad5a35f7133616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E5=85=88=E5=AF=8C?= Date: Fri, 14 May 2021 08:14:01 +0800 Subject: [PATCH 139/177] =?UTF-8?q?0090=20=E5=AD=90=E9=9B=86=E9=97=AE?= =?UTF-8?q?=E9=A2=98II=20Javascript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index cc5fd571..c7d6026e 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -179,6 +179,36 @@ Python: Go: +Javascript: + +```Javascript + +var subsetsWithDup = function(nums) { + let result = [] + let path = [] + let sortNums = nums.sort((a, b) => { + return a - b + }) + function backtracing(startIndex, sortNums) { + result.push(path.slice(0)) + if(startIndex > nums.length - 1) { + return + } + for(let i = startIndex; i < nums.length; i++) { + if(i > startIndex && nums[i] === nums[i - 1]) { + continue + } + path.push(nums[i]) + backtracing(i + 1, sortNums) + path.pop() + } + } + backtracing(0, sortNums) + return result +}; + +``` + From 0cb990ac45463b350e0d825bf23263c4ce5e904b Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Fri, 14 May 2021 09:38:34 +0800 Subject: [PATCH 140/177] =?UTF-8?q?Update=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 5f7b1ac0..0d7e7e92 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -153,7 +153,36 @@ Python: Go: +```Go +var result [][]int +func backtrack(nums,pathNums []int,used []bool){ + if len(nums)==len(pathNums){ + tmp:=make([]int,len(nums)) + copy(tmp,pathNums) + result=append(result,tmp) + //result=append(result,pathNums) + return + } + for i:=0;i Date: Fri, 14 May 2021 09:57:28 +0800 Subject: [PATCH 141/177] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8a9d748..e3d9bc62 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -145,7 +145,29 @@ Python: Go: +```Go +func maxSubArray(nums []int) int { + if len(nums)<1{ + return 0 + } + dp:=make([]int,len(nums)) + result:=nums[0] + dp[0]=nums[0] + for i:=1;ib{ + return a + }else{ + return b + } +} +``` From 1acffe8867ef6699d059871972575fb15a30e4e3 Mon Sep 17 00:00:00 2001 From: Naxx-C <74910279+Naxx-C@users.noreply.github.com> Date: Fri, 14 May 2021 11:31:19 +0800 Subject: [PATCH 142/177] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d9ecfc12..e975ef53 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -201,6 +201,21 @@ public: } return s; } + + /* 主函数简单写法 + string reverseWords(string s) { + removeExtraSpaces(s); + reverse(s, 0, s.size() - 1); + for(int i = 0; i < s.size(); i++) { + int j = i; + // 查找单词间的空格,翻转单词 + while(j < s.size() && s[j] != ' ') j++; + reverse(s, i, j - 1); + i = j; + } + return s; + } + */ }; ``` From a634dbd747ae106a70cf4284b2536fe6df408adf Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Fri, 14 May 2021 12:28:43 +0800 Subject: [PATCH 143/177] Update --- README.md | 38 ++++++--- problems/数组理论基础.md | 15 ---- problems/面试题02.07.链表相交.md | 109 ++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 28 deletions(-) create mode 100644 problems/面试题02.07.链表相交.md diff --git a/README.md b/README.md index 276c8313..7eba656d 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,17 @@ 很多刚开始刷题的同学都有一个困惑:面对leetcode上近两千道题目,从何刷起。 +大家平时刷题感觉效率低,浪费的时间主要在三点: + +* 找题 +* 找到了不应该现阶段做的题 +* 没有全套的优质题解可以参考 + 其实我之前在知乎上回答过这个问题,回答内容大概是按照如下类型来刷数组-> 链表-> 哈希表->字符串->栈与队列->树->回溯->贪心->动态规划->图论->高级数据结构,再从简单刷起,做了几个类型题目之后,再慢慢做中等题目、困难题目。 但我能设身处地的感受到:即使有这样一个整体规划,对于一位初学者甚至算法老手寻找合适自己的题目也是很困难,时间成本很高,而且题目还不一定就是经典题目。 -对于刷题,我们都是想用最短的时间把经典题目都做一篇,这样效率才是最高的! +对于刷题,我们都是想用最短的时间**按照循序渐进的难度顺序把经典题目都做一遍**,这样效率才是最高的! 所以我整理了leetcode刷题攻略:一个超级详细的刷题顺序,**每道题目都是我精心筛选,都是经典题目高频面试题**,大家只要按照这个顺序刷就可以了,**你没看错,就是题目顺序都排好了,文章顺序就是刷题顺序!挨个刷就可以,不用自己再去题海里选题了!** @@ -49,15 +55,18 @@ **目前已经更新了,数组-> 链表-> 哈希表->字符串->栈与队列->树->回溯->贪心,八个专题了,正在讲解动态规划!** -在刷题指南中,每个专题开始都有理论基础篇,并不像是教科书般的理论介绍,而是从实战中归纳需要的基础知识。每个专题结束都有总结篇,最这个专题的归纳总结。 +在刷题攻略中,每个专题开始都有理论基础篇,并不像是教科书般的理论介绍,而是从实战中归纳需要的基础知识。每个专题结束都有总结篇,最这个专题的归纳总结。 如果你是算法老手,这篇攻略也是复习的最佳资料,如果把每个系列对应的总结篇,快速过一遍,整个算法知识体系以及各种解法就重现脑海了。 -在按照如下顺序刷题的过程中,每一道题解一定要看对应文章下面的留言(留言目前只能在手机端查看)。 -如果你有疑问或者发现文章哪里有不对的地方,都可以在留言区都能找到答案,还有很多录友的总结非常赞,看完之后也很有收获。 +目前「代码随想录」刷题攻略更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,部分难点题目还搭配了20分钟左右的视频讲解**。 -目前「代码随想录」刷题指南更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,部分难点题目还搭配了20分钟左右的视频讲解**。 +**这里每一篇题解,都是精品,值得仔细琢磨**。 + +我在题目讲解中统一用C++语言,但你会发现下面几乎每篇题解都配有其他语言版本,Java、Python、Go、JavaScript等等,这正是热心小伙们的贡献的代码,当然我也会严格把控代码质量。 + +**所以也欢迎大家参与进来,完善题解的各个语言版本,拥抱开源,让更多小伙伴们收益**。 准备好了么,刷题攻略开始咯,go go go! @@ -66,7 +75,7 @@ ## 前序 * [「代码随想录」后序安排](https://mp.weixin.qq.com/s/4eeGJREy6E-v6D7cR_5A4g) -* [「代码随想录」学习社区](https://mp.weixin.qq.com/s/X1XCH-KevURi3LnakJsCkA) +* [「代码随想录」学习社区](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) * 编程语言 @@ -119,8 +128,9 @@ 4. [链表:听说过两天反转链表又写不出来了?](./problems/0206.翻转链表.md) 5. [链表:两两交换链表中的节点](./problems/0024.两两交换链表中的节点.md) 6. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) -7. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) -8. [链表:总结篇!](./problems/链表总结篇.md) +7. [链表:链表相交](./problems/面试题02.07.链表相交.md) +8. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) +9. [链表:总结篇!](./problems/链表总结篇.md) ## 哈希表 @@ -156,11 +166,13 @@ 3. [字符串:替换空格](./problems/剑指Offer05.替换空格.md) 4. [字符串:花式反转还不够!](./problems/0151.翻转字符串里的单词.md) 5. [链表:听说过两天反转链表又写不出来了?](./problems/0206.翻转链表.md) -6. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) -7. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) -8. [哈希表:解决了两数之和,那么能解决三数之和么?](./problems/0015.三数之和.md) -9. [双指针法:一样的道理,能解决四数之和](./problems/0018.四数之和.md) -10. [双指针法:总结篇!](./problems/双指针总结.md) +6. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) +7. [链表:链表相交](./problems/面试题02.07.链表相交.md) +8. [链表:环找到了,那入口呢?](./problems/0142.环形链表II.md) +9. [链表:删除链表的倒数第 N 个结点](./problems/0019.删除链表的倒数第N个节点.md) +10. [哈希表:解决了两数之和,那么能解决三数之和么?](./problems/0015.三数之和.md) +11. [双指针法:一样的道理,能解决四数之和](./problems/0018.四数之和.md) +12. [双指针法:总结篇!](./problems/双指针总结.md) ## 栈与队列 diff --git a/problems/数组理论基础.md b/problems/数组理论基础.md index f061088f..a2c86ac4 100644 --- a/problems/数组理论基础.md +++ b/problems/数组理论基础.md @@ -118,21 +118,6 @@ public static void test_arr() { 这里面试中数组相关的理论知识就介绍完了。 -后续我将介绍面试中数组相关的五道经典面试题目,敬请期待! - - -## 其他语言版本 - - -Java: - - -Python: - - -Go: - - ----------------------- diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md new file mode 100644 index 00000000..97045ed2 --- /dev/null +++ b/problems/面试题02.07.链表相交.md @@ -0,0 +1,109 @@ + +

+ + + + +

+

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ +## 面试题 02.07. 链表相交 + +题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/ + +给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。 + +示例 1: + +输入:listA = [4,1,8,4,5], listB = [5,0,1,8,4,5] + +输出:Reference of the node with value = 8 + +输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。 + + +## 思路 + +本来很简洁明了的一道题,让题目描述搞的云里雾里的。 + +简单来说,就是求两个链表交点节点的**指针**。 这里同学们要注意,交点不是数值相等,而是指针相等。 + +为了方便举例,假设节点元素数值相等,则节点指针相等。 + +看如下两个链表,目前curA指向链表A的头结点,curB指向链表B的头结点: + +![面试题02.07.链表相交_1](https://code-thinking.cdn.bcebos.com/pics/%E9%9D%A2%E8%AF%95%E9%A2%9802.07.%E9%93%BE%E8%A1%A8%E7%9B%B8%E4%BA%A4_1.png)v + +我们求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置,如图: + +![面试题02.07.链表相交_2](https://code-thinking.cdn.bcebos.com/pics/%E9%9D%A2%E8%AF%95%E9%A2%9802.07.%E9%93%BE%E8%A1%A8%E7%9B%B8%E4%BA%A4_2.png) + +此时我们就可以比较curA和curB是否相同,如果不相同,同时向后移动curA和curB,如果遇到curA == curB,则找到焦点。 + +否则循环退出返回空指针。 + +C++代码如下: + +```C++ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode* curA = headA; + ListNode* curB = headB; + int lenA = 0, lenB = 0; + while (curA != NULL) { // 求链表A的长度 + lenA++; + curA = curA->next; + } + while (curB != NULL) { // 求链表B的长度 + lenB++; + curB = curB->next; + } + curA = headA; + curB = headB; + // 让curA为最长链表的头,lenA为其长度 + if (lenB > lenA) { + swap (lenA, lenB); + swap (curA, curB); + } + // 求长度差 + int gap = lenA - lenB; + // 让curA和curB在同一起点上(末尾位置对齐) + while (gap--) { + curA = curA->next; + } + // 遍历curA 和 curB,遇到相同则直接返回 + while (curA != NULL) { + if (curA == curB) { + return curA; + } + curA = curA->next; + curB = curB->next; + } + return NULL; + } +}; +``` + +* 时间复杂度:$O(n + m)$ +* 空间复杂度:$O(1)$ + +## 其他语言版本 + + +Java: + + +Python: + + +Go: + + + + +----------------------- +* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) +* B站视频:[代码随想录](https://space.bilibili.com/525438321) +* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +
From 8eaba5884f9d499275c7c549eb4d846e8032fdc4 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Fri, 14 May 2021 15:03:44 +0800 Subject: [PATCH 144/177] =?UTF-8?q?Update=200051.N=E7=9A=87=E5=90=8E.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index ac0235c2..935ea89c 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -363,7 +363,72 @@ Python: Go: +```Go +import "strings" +var res [][]string +func isValid(board [][]string, row, col int) (res bool){ + n := len(board) + for i:=0; i < row; i++ { + if board[i][col] == "Q" { + return false + } + } + for i := 0; i < n; i++{ + if board[row][i] == "Q" { + return false + } + } + + for i ,j := row, col; i >= 0 && j >=0 ; i, j = i - 1, j- 1{ + if board[i][j] == "Q"{ + return false + } + } + for i, j := row, col; i >=0 && j < n; i,j = i-1, j+1 { + if board[i][j] == "Q" { + return false + } + } + return true +} + +func backtrack(board [][]string, row int) { + size := len(board) + if row == size{ + temp := make([]string, size) + for i := 0; i Date: Fri, 14 May 2021 15:28:50 +0800 Subject: [PATCH 145/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00106.=E4=BB=8E?= =?UTF-8?q?=E4=B8=AD=E5=BA=8F=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=20JavaScript=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...中序与后序遍历序列构造二叉树.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index e51cf08b..4cc2a88a 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -623,7 +623,21 @@ Python: Go: - +JavaScript +```javascript +var buildTree = function(inorder, postorder) { + if (!postorder.length) return null + + let root = new TreeNode(postorder[postorder.length - 1]) + + let index = inorder.findIndex(number => number === root.val) + + root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index)) + root.right = buildTree(inorder.slice(index + 1, inorder.length), postorder.slice(index, postorder.length - 1)) + + return root +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) From f9535fac720c4331df5b42a92fa77e8e66b21135 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Fri, 14 May 2021 15:37:50 +0800 Subject: [PATCH 146/177] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=B8=BB=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E7=B2=BE=E7=AE=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 21 +++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index e975ef53..1c567f84 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -141,7 +141,8 @@ void reverse(string& s, int start, int end) { -``` +```C++ +// 版本一 class Solution { public: // 反转字符串s中左闭又闭的区间[start, end] @@ -219,6 +220,24 @@ public: }; ``` +当然这里的主函数reverseWords写的有一些冗余的,可以精简一些,精简之后的主函数为: + +```C++ +// 注意这里仅仅是主函数,其他函数和版本一一致 +string reverseWords(string s) { + removeExtraSpaces(s); + reverse(s, 0, s.size() - 1); + for(int i = 0; i < s.size(); i++) { + int j = i; + // 查找单词间的空格,翻转单词 + while(j < s.size() && s[j] != ' ') j++; + reverse(s, i, j - 1); + i = j; + } + return s; +} +``` + From 62f7d624335168bf013a842305c24fca21fb31b7 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Fri, 14 May 2021 15:58:58 +0800 Subject: [PATCH 147/177] =?UTF-8?q?Update=200072.=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E8=B7=9D=E7=A6=BB.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0072.编辑距离.md | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 8e6e0187..7e27a3d5 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -204,7 +204,40 @@ Python: Go: - +```Go +func minDistance(word1 string, word2 string) int { + m, n := len(word1), len(word2) + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 0; i < m+1; i++ { + dp[i][0] = i // word1[i] 变成 word2[0], 删掉 word1[i], 需要 i 部操作 + } + for j := 0; j < n+1; j++ { + dp[0][j] = j // word1[0] 变成 word2[j], 插入 word1[j],需要 j 部操作 + } + for i := 1; i < m+1; i++ { + for j := 1; j < n+1; j++ { + if word1[i-1] == word2[j-1] { + dp[i][j] = dp[i-1][j-1] + } else { // Min(插入,删除,替换) + dp[i][j] = Min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1 + } + } + } + return dp[m][n] +} +func Min(args ...int) int { + min := args[0] + for _, item := range args { + if item < min { + min = item + } + } + return min +} +``` From 4291679c21575f938b63061bcb80739769fc47d6 Mon Sep 17 00:00:00 2001 From: weikunkun Date: Fri, 14 May 2021 17:08:19 +0800 Subject: [PATCH 148/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A00072.=E7=BC=96?= =?UTF-8?q?=E8=BE=91=E8=B7=9D=E7=A6=BB=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0072.编辑距离.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 7e27a3d5..32c888f1 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -198,7 +198,32 @@ public: Java: - +```java +public int minDistance(String word1, String word2) { + int m = word1.length(); + int n = word2.length(); + int[][] dp = new int[m + 1][n + 1]; + // 初始化 + for (int i = 1; i <= m; i++) { + dp[i][0] = i; + } + for (int j = 1; j <= n; j++) { + dp[0][j] = j; + } + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + // 因为dp数组有效位从1开始 + // 所以当前遍历到的字符串的位置为i-1 | j-1 + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1; + } + } + } + return dp[m][n]; +} +``` Python: From a838937b6d3d213c1cde59f72203126fa43b9dc5 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Fri, 14 May 2021 19:40:41 +0800 Subject: [PATCH 149/177] =?UTF-8?q?Update=200647.=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E5=AD=90=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index fbc9133e..45bb72be 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -227,6 +227,30 @@ Python: Go: +```Go +func countSubstrings(s string) int { + res:=0 + dp:=make([][]bool,len(s)) + for i:=0;i=0;i--{ + for j:=i;j Date: Fri, 14 May 2021 22:13:43 +0800 Subject: [PATCH 150/177] =?UTF-8?q?Update=200045.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8FII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0045.跳跃游戏II.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index b8e369e6..f65ceb9e 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -175,7 +175,22 @@ class Solution { ``` Python: - +```python +class Solution: + def jump(self, nums: List[int]) -> int: + if len(nums) == 1: return 0 + ans = 0 + curDistance = 0 + nextDistance = 0 + for i in range(len(nums)): + nextDistance = max(i + nums[i], nextDistance) + if i == curDistance: + if curDistance != len(nums) - 1: + ans += 1 + curDistance = nextDistance + if nextDistance >= len(nums) - 1: break + return ans +``` Go: From 63e2a42d5b60220f064a241a4a6f85e3536d8baf Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Sat, 15 May 2021 00:04:20 +0800 Subject: [PATCH 151/177] =?UTF-8?q?Update=201005.K=E6=AC=A1=E5=8F=96?= =?UTF-8?q?=E5=8F=8D=E5=90=8E=E6=9C=80=E5=A4=A7=E5=8C=96=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- .../1005.K次取反后最大化的数组和.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 1653201e..89ed9176 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -124,7 +124,18 @@ class Solution { ``` Python: - +```python +class Solution: + def largestSumAfterKNegations(self, A: List[int], K: int) -> int: + A = sorted(A, key=abs, reverse=True) # 将A按绝对值从大到小排列 + for i in range(len(A)): + if K > 0 and A[i] < 0: + A[i] *= -1 + K -= 1 + if K > 0: + A[len(A) - 1] *= ((-1)**K) + return sum(A) +``` Go: @@ -135,4 +146,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 +
From 2b5319631cbae953609c691269668f18e602a632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E5=85=88=E5=AF=8C?= Date: Sat, 15 May 2021 09:25:24 +0800 Subject: [PATCH 152/177] =?UTF-8?q?0491.=E9=80=92=E5=A2=9E=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97.md=20Javascript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 5deec0ee..20dcb524 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -207,6 +207,34 @@ Python: Go: +Javascript: + +```Javascript + +var findSubsequences = function(nums) { + let result = [] + let path = [] + function backtracing(startIndex) { + if(path.length > 1) { + result.push(path.slice()) + } + let uset = [] + for(let i = startIndex; i < nums.length; i++) { + if((path.length > 0 && nums[i] < path[path.length - 1]) || uset[nums[i] + 100]) { + continue + } + uset[nums[i] + 100] = true + path.push(nums[i]) + backtracing(i + 1) + path.pop() + } + } + backtracing(0) + return result +}; + +``` + From 039174e723c33526fd07a82a3abcfe9cc1089727 Mon Sep 17 00:00:00 2001 From: gdnlnsjd <84071244+gdnlnsjd@users.noreply.github.com> Date: Sat, 15 May 2021 10:30:54 +0800 Subject: [PATCH 153/177] =?UTF-8?q?Update=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 5f7b1ac0..0b3174f0 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -147,6 +147,30 @@ public: Java: +class Solution { + List> result=new ArrayList>(); + Deque path=new LinkedList(); + void backtracking(int []nums,Boolean []used) { + if(path.size()==nums.length) { + result.add(new ArrayList(path)); + return; + } + for(int i=0;i> permute(int[] nums) { + Boolean []used=new Boolean[nums.length]; + for(int i=0;i Date: Sat, 15 May 2021 10:32:59 +0800 Subject: [PATCH 154/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20070=E7=88=AC?= =?UTF-8?q?=E6=A5=BC=E6=A2=AF=20Java=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index f0a08f99..286e088f 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -213,6 +213,28 @@ public: Java: +```java +// 常规方式 +public int climbStairs(int n) { + int[] dp = new int[n + 1]; + dp[0] = 1; + dp[1] = 1; + for (int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; +} +// 用变量记录代替数组 +public int climbStairs(int n) { + int a = 0, b = 1, c = 0; // 默认需要1次 + for (int i = 1; i <= n; i++) { + c = a + b; // f(i - 1) + f(n - 2) + a = b; // 记录上一轮的值 + b = c; // 向后步进1个数 + } + return c; +} +``` Python: From dc1dc8fe8429e81a097eebfdb9f87d4b980adbd3 Mon Sep 17 00:00:00 2001 From: gdnlnsjd <84071244+gdnlnsjd@users.noreply.github.com> Date: Sat, 15 May 2021 10:44:49 +0800 Subject: [PATCH 155/177] =?UTF-8?q?Update=200046.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 0b3174f0..373c9257 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -147,6 +147,7 @@ public: Java: +```java class Solution { List> result=new ArrayList>(); Deque path=new LinkedList(); @@ -171,7 +172,7 @@ class Solution { return result; } } - +``` Python: From 9ceecd50b679fd215c778f64c49baa4f83b8c5fb Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 10:51:53 +0800 Subject: [PATCH 156/177] =?UTF-8?q?0020=20=E6=9C=89=E6=95=88=E6=8B=AC?= =?UTF-8?q?=E5=8F=B7=E5=A2=9E=E5=8A=A0Java=E6=96=B0=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 77c6e10a..98cc7cd8 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -162,6 +162,33 @@ class Solution { return deque.isEmpty(); } } +// 方法2 +class Solution { + public boolean isValid(String s) { + + Stack stack = new Stack<>(); + Map map = new HashMap() { + { + put('}', '{'); + put(']', '['); + put(')', '('); + } + }; + + for (Character c : s.toCharArray()) { // 顺序读取字符 + if (!stack.isEmpty() && map.containsKey(c)) { // 是右括号 && 栈不为空 + if (stack.peek() == map.get(c)) { // 取其对应的左括号直接和栈顶比 + stack.pop(); // 相同则抵消,出栈 + } else { + return false; // 不同则直接返回 + } + } else { + stack.push(c); // 左括号,直接入栈 + } + } + return stack.isEmpty(); // 看左右是否抵消完 + } +} ``` Python: From 060f1eadb35507f4d8b9a51ae0eb65ac215fc5d4 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:02:29 +0800 Subject: [PATCH 157/177] =?UTF-8?q?0024=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?=20=E6=B7=BB=E5=8A=A0Java=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 9f07b4f7..0cfa7fb9 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -86,7 +86,27 @@ public: Java: +```java +// 虚拟头结点 +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummyNode = new ListNode(0); + dummyNode.next = head; + ListNode prev = dummyNode; + + while (prev.next != null && prev.next.next != null) { + ListNode temp = head.next.next; // 缓存 next + prev.next = head.next; // 将 prev 的 next 改为 head 的 next + head.next.next = head; // 将 head.next(prev.next) 的next,指向 head + head.next = temp; // 将head 的 next 接上缓存的temp + prev = head; // 步进1位 + head = head.next; // 步进1位 + } + return dummyNode.next; + } +} +``` Python: From 8dedebcc8da5b715e44e0d8ee2dbcceedcaeef11 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:10:47 +0800 Subject: [PATCH 158/177] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=2098=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91Java?= =?UTF-8?q?=E7=AE=80=E6=B4=81=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index f246c21a..d8945eff 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -304,6 +304,35 @@ class Solution { return true; } } + +// 简洁实现·递归解法 +class Solution { + public boolean isValidBST(TreeNode root) { + return validBST(Long.MIN_VALUE, Long.MAX_VALUE, root); + } + boolean validBST(long lower, long upper, TreeNode root) { + if (root == null) return true; + if (root.val <= lower || root.val >= upper) return false; + return validBST(lower, root.val, root.left) && validBST(root.val, upper, root.right); + } +} +// 简洁实现·中序遍历 +class Solution { + private long prev = Long.MIN_VALUE; + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + if (!isValidBST(root.left)) { + return false; + } + if (root.val <= prev) { // 不满足二叉搜索树条件 + return false; + } + prev = root.val; + return isValidBST(root.right); + } +} ``` Python: From b83f378bee5f954c7d64fcac44fac03fb0387cf5 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:19:14 +0800 Subject: [PATCH 159/177] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200112=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E5=92=8CJava=20=E7=AE=80=E6=B4=81=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 1b75113e..ecbefd90 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -332,6 +332,19 @@ class Solution { } } +// LC112 简洁方法 +class Solution { + public boolean hasPathSum(TreeNode root, int targetSum) { + + if (root == null) return false; // 为空退出 + + // 叶子节点判断是否符合 + if (root.left == null && root.right == null) return root.val == targetSum; + + // 求两侧分支的路径和 + return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); + } +} ``` Python: From b7836d951f518ba437ed69863bbb3cf5fcc75638 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:25:22 +0800 Subject: [PATCH 160/177] =?UTF-8?q?0121=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=20Java=20=E7=89=88=E6=9C=AC=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 3d564892..a0b35090 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -198,7 +198,22 @@ public: Java: - +```java +class Solution { + public int maxProfit(int[] prices) { + int minprice = Integer.MAX_VALUE; + int maxprofit = 0; + for (int i = 0; i < prices.length; i++) { + if (prices[i] < minprice) { + minprice = prices[i]; + } else if (prices[i] - minprice > maxprofit) { + maxprofit = prices[i] - minprice; + } + } + return maxprofit; + } +} +``` Python: From ec61f2430d3ab09f8dc1c998514dfc1ca77ba0bb Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:30:14 +0800 Subject: [PATCH 161/177] =?UTF-8?q?0122=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA2=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Java=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...票的最佳时机II(动态规划).md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 3444ca73..c85272bc 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -133,7 +133,34 @@ public: Java: +```java +// 动态规划 +class Solution + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] dp = new int[n][2]; + dp[0][0] = 0; + dp[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); + } + return dp[n - 1][0]; + } + public int maxProfit(int[] prices) { + int n = prices.length; + int dp0 = 0, dp1 = -prices[0]; + for (int i = 1; i < n; ++i) { + int newDp0 = Math.max(dp0, dp1 + prices[i]); + int newDp1 = Math.max(dp1, dp0 - prices[i]); + dp0 = newDp0; + dp1 = newDp1; + } + return dp0; + } +} +``` Python: From 92992f05904788e8249f142f2b3eb5b6ad1c5ec4 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:43:00 +0800 Subject: [PATCH 162/177] =?UTF-8?q?0198=20=E6=89=93=E5=AE=B6=E5=8A=AB?= =?UTF-8?q?=E8=88=8D=E6=B7=BB=E5=8A=A0=20Java=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0198.打家劫舍.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index c64648ad..649dd055 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -111,7 +111,24 @@ public: Java: +```Java +// 动态规划 +class Solution { + public int rob(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + int[] dp = new int[nums.length + 1]; + dp[0] = nums[0]; + dp[1] = Math.max(dp[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + } + + return dp[nums.length - 1]; + } +} +``` Python: From 430d46749408f0d59bcce006c26f49a1c84fe04e Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:47:15 +0800 Subject: [PATCH 163/177] =?UTF-8?q?Update=200213.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8DII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0213.打家劫舍II.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 55e71bc0..fc58a065 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -98,7 +98,28 @@ public: Java: +```Java +class Solution { + public int rob(int[] nums) { + if (nums == null || nums.length == 0) + return 0; + int len = nums.length; + if (len == 1) + return nums[0]; + return Math.max(robAction(nums, 0, len - 1), robAction(nums, 1, len)); + } + int robAction(int[] nums, int start, int end) { + int x = 0, y = 0, z = 0; + for (int i = start; i < end; i++) { + y = z; + z = Math.max(y, x + nums[i]); + x = y; + } + return z; + } +} +``` Python: From 335c4adcdfdf7e5d2a20c2a42bd0070b1356a24a Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:55:37 +0800 Subject: [PATCH 164/177] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0300.最长上升子序列.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 2bc5cf9c..1cdc48b9 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -110,7 +110,26 @@ public: Java: - +```Java +class Solution { + public int lengthOfLIS(int[] nums) { + int[] dp = new int[nums.length]; + Arrays.fill(dp, 1); + for (int i = 0; i < dp.length; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + } + int res = 0; + for (int i = 0; i < dp.length; i++) { + res = Math.max(res, dp[i]); + } + return res; + } +} +``` Python: From 9dc03f28f0924acea1bab037fbe3de986facbf51 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Sat, 15 May 2021 11:58:33 +0800 Subject: [PATCH 165/177] =?UTF-8?q?Update=200150.=E9=80=86=E6=B3=A2?= =?UTF-8?q?=E5=85=B0=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 27 ++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 4e7365f7..12977c39 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -170,7 +170,32 @@ public class EvalRPN { } ``` - +Go: +```Go +func evalRPN(tokens []string) int { + stack := []int{} + for _, token := range tokens { + val, err := strconv.Atoi(token) + if err == nil { + stack = append(stack, val) + } else { + num1, num2 := stack[len(stack)-2], stack[(len(stack))-1] + stack = stack[:len(stack)-2] + switch token { + case "+": + stack = append(stack, num1+num2) + case "-": + stack = append(stack, num1-num2) + case "*": + stack = append(stack, num1*num2) + case "/": + stack = append(stack, num1/num2) + } + } + } + return stack[0] +} +``` From d4e756ba6f7d23db9b474562e6c5899237290c4b Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:59:55 +0800 Subject: [PATCH 166/177] =?UTF-8?q?Update=200337.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8DIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0337.打家劫舍III.md | 65 ++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index 50b06e22..20eea817 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -218,7 +218,72 @@ public: Java: +```Java +class Solution { + // 1.递归去偷,超时 + public int rob(TreeNode root) { + if (root == null) + return 0; + int money = root.val; + if (root.left != null) { + money += rob(root.left.left) + rob(root.left.right); + } + if (root.right != null) { + money += rob(root.right.left) + rob(root.right.right); + } + return Math.max(money, rob(root.left) + rob(root.right)); + } + // 2.递归去偷,记录状态 + // 执行用时:3 ms , 在所有 Java 提交中击败了 56.24% 的用户 + public int rob1(TreeNode root) { + Map memo = new HashMap<>(); + return robAction(root, memo); + } + + int robAction(TreeNode root, Map memo) { + if (root == null) + return 0; + if (memo.containsKey(root)) + return memo.get(root); + int money = root.val; + if (root.left != null) { + money += robAction(root.left.left, memo) + robAction(root.left.right, memo); + } + if (root.right != null) { + money += robAction(root.right.left, memo) + robAction(root.right.right, memo); + } + int res = Math.max(money, robAction(root.left, memo) + robAction(root.right, memo)); + memo.put(root, res); + return res; + } + + // 3.状态标记递归 + // 执行用时:0 ms , 在所有 Java 提交中击败了 100% 的用户 + // 不偷:Max(左孩子不偷,左孩子偷) + Max(又孩子不偷,右孩子偷) + // root[0] = Math.max(rob(root.left)[0], rob(root.left)[1]) + + // Math.max(rob(root.right)[0], rob(root.right)[1]) + // 偷:左孩子不偷+ 右孩子不偷 + 当前节点偷 + // root[1] = rob(root.left)[0] + rob(root.right)[0] + root.val; + public int rob3(TreeNode root) { + int[] res = robAction1(root); + return Math.max(res[0], res[1]); + } + + int[] robAction1(TreeNode root) { + int res[] = new int[2]; + if (root == null) + return res; + + int[] left = robAction1(root.left); + int[] right = robAction1(root.right); + + res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); + res[1] = root.val + left[0] + right[0]; + return res; + } +} +``` Python: From 1a962286b8c4829b1378b8442f2be07adf59c6db Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 12:02:59 +0800 Subject: [PATCH 167/177] =?UTF-8?q?Update=200509.=E6=96=90=E6=B3=A2?= =?UTF-8?q?=E9=82=A3=E5=A5=91=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0509.斐波那契数.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 8537ed8b..8be11312 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -171,7 +171,20 @@ public: Java: - +```Java +class Solution { + public int fib(int n) { + if (n < 2) return n; + int a = 0, b = 1, c = 0; + for (int i = 1; i < n; i++) { + c = a + b; + a = b; + b = c; + } + return c; + } +} +``` Python: From a560255502699162a4b1ca667f4bd91aad17ced2 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 12:11:00 +0800 Subject: [PATCH 168/177] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 02d4b060..e8cf0bdd 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -115,7 +115,59 @@ void traversal(TreeNode* cur, vector& vec) { Java: +```Java +// 前序遍历·递归·LC144_二叉树的前序遍历 +class Solution { + ArrayList preOrderReverse(TreeNode root) { + ArrayList result = new ArrayList(); + preOrder(root, result); + return result; + } + void preOrder(TreeNode root, ArrayList result) { + if (root == null) { + return; + } + result.add(root.val); // 注意这一句 + preOrder(root.left, result); + preOrder(root.right, result); + } +} +// 中序遍历·递归·LC94_二叉树的中序遍历 +class Solution { + public List inorderTraversal(TreeNode root) { + List res = new ArrayList<>(); + inorder(root, res); + return res; + } + + void inorder(TreeNode root, List list) { + if (root == null) { + return; + } + inorder(root.left, list); + list.add(root.val); // 注意这一句 + inorder(root.right, list); + } +} +// 后序遍历·递归·LC145_二叉树的后序遍历 +class Solution { + public List postorderTraversal(TreeNode root) { + List res = new ArrayList<>(); + postorder(root, res); + return res; + } + + void postorder(TreeNode root, List list) { + if (root == null) { + return; + } + postorder(root.left, list); + postorder(root.right, list); + list.add(root.val); // 注意这一句 + } +} +``` Python: From bd707f89381c9202e8c5bca784551c73ed9cb08c Mon Sep 17 00:00:00 2001 From: kyrie <783842766@qq.com> Date: Sat, 15 May 2021 12:30:37 +0800 Subject: [PATCH 169/177] =?UTF-8?q?Update=200070.=E7=88=AC=E6=A5=BC?= =?UTF-8?q?=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0070.爬楼梯 Java版本 --- problems/0070.爬楼梯.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index f0a08f99..3f14075f 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -212,6 +212,22 @@ public: Java: +```Java +class Solution { + public int climbStairs(int n) { + // 跟斐波那契数列一样 + if(n <= 2) return n; + int a = 1, b = 2, sum = 0; + + for(int i = 3; i <= n; i++){ + sum = a + b; + a = b; + b = sum; + } + return b; + } +} +``` Python: From 66cd7012705cfabf2604329bcdc7a34a12541797 Mon Sep 17 00:00:00 2001 From: kyrie <783842766@qq.com> Date: Sat, 15 May 2021 12:43:12 +0800 Subject: [PATCH 170/177] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4?= =?UTF-8?q?=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0024.两两交换链表中的节点 Java递归版本 --- problems/0024.两两交换链表中的节点.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 9f07b4f7..58cd3d8a 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -86,6 +86,23 @@ public: Java: +```Java +class Solution { + public ListNode swapPairs(ListNode head) { + // base case 退出提交 + if(head == null || head.next == null) return head; + // 获取当前节点的下一个节点 + ListNode next = head.next; + // 进行递归 + ListNode newNode = swapPairs(next.next); + // 这里进行交换 + next.next = head; + head.next = newNode; + + return next; + } +} +``` Python: From f569c710e299b833242756903757b18738727213 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Sat, 15 May 2021 17:50:32 +0800 Subject: [PATCH 171/177] =?UTF-8?q?Update=200077.=E7=BB=84=E5=90=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 3dfb5216..3e840cd2 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -346,6 +346,32 @@ Python: Go: +```Go +var res [][]int +func combine(n int, k int) [][]int { + res=[][]int{} + if n <= 0 || k <= 0 || k > n { + return res + } + backtrack(n, k, 1, []int{}) + return res +} +func backtrack(n,k,start int,track []int){ + if len(track)==k{ + temp:=make([]int,k) + copy(temp,track) + res=append(res,temp) + } + if len(track)+n-start+1 < k { + return + } + for i:=start;i<=n;i++{ + track=append(track,i) + backtrack(n,k,i+1,track) + track=track[:len(track)-1] + } +} +``` From c6ce4763e0928b7d5aca28e6a26357e740792d80 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 19:11:36 +0800 Subject: [PATCH 172/177] =?UTF-8?q?=E4=B8=BA=200122=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?II=20Java=E4=BB=A3=E7=A0=81=E6=B7=BB=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...票的最佳时机II(动态规划).md | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index c85272bc..e3526ecf 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -136,24 +136,31 @@ Java: ```java // 动态规划 class Solution + // 实现1:二维数组存储 + // 可以将每天持有与否的情况分别用 dp[i][0] 和 dp[i][1] 来进行存储 + // 时间复杂度:O(n),空间复杂度O(n) public int maxProfit(int[] prices) { int n = prices.length; - int[][] dp = new int[n][2]; - dp[0][0] = 0; + int[][] dp = new int[n][2]; // 创建二维数组存储状态 + dp[0][0] = 0; // 初始状态 dp[0][1] = -prices[0]; for (int i = 1; i < n; ++i) { - dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); - dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); // 第 i 天,没有股票 + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]); // 第 i 天,持有股票 } - return dp[n - 1][0]; + return dp[n - 1][0]; // 卖出股票收益高于持有股票收益,因此取[0] } + // 实现2:变量存储 + // 第一种方法需要用二维数组存储,有空间开销,其实关心的仅仅是前一天的状态,不关注更多的历史信息 + // 因此,可以仅保存前一天的信息存入 dp0、dp1 这 2 个变量即可 + // 时间复杂度:O(n),空间复杂度O(1) public int maxProfit(int[] prices) { int n = prices.length; - int dp0 = 0, dp1 = -prices[0]; + int dp0 = 0, dp1 = -prices[0]; // 定义变量,存储初始状态 for (int i = 1; i < n; ++i) { - int newDp0 = Math.max(dp0, dp1 + prices[i]); - int newDp1 = Math.max(dp1, dp0 - prices[i]); + int newDp0 = Math.max(dp0, dp1 + prices[i]); // 第 i 天,没有股票 + int newDp1 = Math.max(dp1, dp0 - prices[i]); // 第 i 天,持有股票 dp0 = newDp0; dp1 = newDp1; } From 3c0ceba0644a38d6aa35125809d85b5afaf2419e Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Sat, 15 May 2021 23:11:10 +0800 Subject: [PATCH 173/177] =?UTF-8?q?Update=200134.=E5=8A=A0=E6=B2=B9?= =?UTF-8?q?=E7=AB=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0134.加油站.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index 393e4627..52019aec 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -223,7 +223,21 @@ class Solution { ``` Python: - +```python +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + start = 0 + curSum = 0 + totalSum = 0 + for i in range(len(gas)): + curSum += gas[i] - cost[i] + totalSum += gas[i] - cost[i] + if curSum < 0: + curSum = 0 + start = i + 1 + if totalSum < 0: return -1 + return start +``` Go: @@ -234,4 +248,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 +
From 69b766e83ee3ccb191e9b093399a04123b6cd951 Mon Sep 17 00:00:00 2001 From: LiangDazhu <42199191+LiangDazhu@users.noreply.github.com> Date: Sun, 16 May 2021 00:31:42 +0800 Subject: [PATCH 174/177] =?UTF-8?q?Update=200135.=E5=88=86=E5=8F=91?= =?UTF-8?q?=E7=B3=96=E6=9E=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added python version code --- problems/0135.分发糖果.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index fedf8765..51b32965 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -161,7 +161,18 @@ class Solution { ``` Python: - +```python +class Solution: + def candy(self, ratings: List[int]) -> int: + candyVec = [1] * len(ratings) + for i in range(1, len(ratings)): + if ratings[i] > ratings[i - 1]: + candyVec[i] = candyVec[i - 1] + 1 + for j in range(len(ratings) - 2, -1, -1): + if ratings[j] > ratings[j + 1]: + candyVec[j] = max(candyVec[j], candyVec[j + 1] + 1) + return sum(candyVec) +``` Go: @@ -172,4 +183,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 +
From 897396c15ad3b34e2913350689794a4b754f32d9 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Sun, 16 May 2021 11:27:26 +0800 Subject: [PATCH 175/177] =?UTF-8?q?Update=200096.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0096.不同的二叉搜索树.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index 7dea8fb0..dca225bf 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -189,7 +189,18 @@ Python: Go: - +```Go +func numTrees(n int)int{ + dp:=make([]int,n+1) + dp[0]=1 + for i:=1;i<=n;i++{ + for j:=1;j<=i;j++{ + dp[i]+=dp[j-1]*dp[i-j] + } + } + return dp[n] +} +``` From e26026c4ef8102cc5d7456c5a8167f4ca36c574c Mon Sep 17 00:00:00 2001 From: weijiew <49638002+weijiew@users.noreply.github.com> Date: Sun, 16 May 2021 11:33:55 +0800 Subject: [PATCH 176/177] =?UTF-8?q?Update=200047.=E5=85=A8=E6=8E=92?= =?UTF-8?q?=E5=88=97II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 参数写错了,改过之后可以通过。 --- problems/0047.全排列II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index 94bb4df1..d22e441e 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -85,7 +85,7 @@ public: path.clear(); sort(nums.begin(), nums.end()); // 排序 vector used(nums.size(), false); - backtracking(nums, vec, used); + backtracking(nums, used); return result; } }; From 52e40aa3883e76957b7080150f6288029c34f2c0 Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Sun, 16 May 2021 11:49:54 +0800 Subject: [PATCH 177/177] =?UTF-8?q?Update=200121.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index a0b35090..ec277263 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -219,6 +219,31 @@ Python: Go: +```Go +func maxProfit(prices []int) int { + length:=len(prices) + if length==0{return 0} + dp:=make([][]int,length) + for i:=0;ib{ + return a + } + return b +} +```