From 3dda10b12f589a78fb026ef469c788415901b7cd Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Fri, 10 Mar 2023 14:11:11 +0800 Subject: [PATCH 001/116] Update --- problems/0377.组合总和IV二维dp数组.md | 145 -------------------------- 1 file changed, 145 deletions(-) delete mode 100644 problems/0377.组合总和IV二维dp数组.md diff --git a/problems/0377.组合总和IV二维dp数组.md b/problems/0377.组合总和IV二维dp数组.md deleted file mode 100644 index 276329c5..00000000 --- a/problems/0377.组合总和IV二维dp数组.md +++ /dev/null @@ -1,145 +0,0 @@ -# 完全背包的排列问题模拟 - -#### Problem - -1. 排列问题是完全背包中十分棘手的问题。 -2. 其在迭代过程中需要先迭代背包容量,再迭代物品个数,使得其在代码理解上较难入手。 - -#### Contribution - -本文档以力扣上[组合总和IV](https://leetcode.cn/problems/combination-sum-iv/)为例,提供一个二维dp的代码例子,并提供模拟过程以便于理解 - -#### Code - -```cpp -int combinationSum4(vector& nums, int target) { - // 定义背包容量为target,物品个数为nums.size()的dp数组 - // dp[i][j]表示将第0-i个物品添加入排列中,和为j的排列方式 - vector> dp (nums.size(), vector(target+1,0)); - - // 表示有0,1,...,n个物品可选择的情况下,和为0的选择方法为1:什么都不取 - for(int i = 0; i < nums.size(); i++) dp[i][0] = 1; - - // 必须按列遍历,因为右边数组需要知道左边数组最低部的信息(排列问题) - // 后面的模拟可以更清楚的表现这么操作的原因 - for(int i = 1; i <= target; i++){ - for(int j = 0; j < nums.size(); j++){ - // 只有nums[j]可以取的情况 - if(j == 0){ - if(nums[j] > i) dp[j][i] = 0; - // 如果背包容量放不下 那么此时没有排列方式 - else dp[j][i] = dp[nums.size()-1][i-nums[j]]; - // 如果背包容量放的下 全排列方式为dp[最底层][容量-该物品容量]排列方式后面放一个nums[j] - } - // 有多个nums数可以取 - else{ - // 如果背包容量放不下 那么沿用0-j-1个物品的排列方式 - if(nums[j] > i) dp[j][i] = dp[j-1][i]; - // 如果背包容量放得下 在dp[最底层][容量-该物品容量]排列方式后面放一个nums[j]后面放个nums[j] - // INT_MAX避免溢出 - else if(i >= nums[j] && dp[j-1][i] < INT_MAX - dp[nums.size()-1][i-nums[j]]) - dp[j][i] = dp[j-1][i] + dp[nums.size()-1][i-nums[j]]; - } - } - } - // 打印dp数组 - for(int i = 0; i < nums.size(); i++){ - for(int j = 0; j <= target; j++){ - cout< Date: Tue, 28 Mar 2023 09:40:19 +0000 Subject: [PATCH 002/116] =?UTF-8?q?Update=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2II.md=20=E8=A1=A5=E5=85=85=E4=BA=8C=E7=BB=B4d?= =?UTF-8?q?p=E6=95=B0=E7=BB=84=E7=9A=84Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0518.零钱兑换II.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index 3fd03e16..eb5a844c 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -215,6 +215,27 @@ class Solution { } } ``` +```Java +// 二维dp数组版本,方便理解 +class Solution { + public int change(int amount, int[] coins) { + int[][] dp = new int[coins.length][amount + 1]; + // 只有一种硬币的情况 + for (int i = 0; i <= amount; i += coins[0]) { + dp[0][i] = 1; + } + for (int i = 1; i < coins.length; i++) { + for (int j = 0; j <= amount; j++) { + // 第i种硬币使用0~k次,求和 + for (int k = 0; k * coins[i] <= j; k++) { + dp[i][j] += dp[i - 1][j - k * coins[i]]; + } + } + } + return dp[coins.length - 1][amount]; + } +} +``` Python: From b18aba58bcfa66b31fb9d40ffb6805f75f5bd3ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E6=97=A0=E7=BC=BA?= Date: Tue, 28 Mar 2023 22:22:14 +0800 Subject: [PATCH 003/116] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将爬楼梯文件中的中字更正为了种 --- problems/0070.爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index d8246223..a06ee91e 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -72,7 +72,7 @@ dp[i]: 爬到第i层楼梯,有dp[i]种方法 3. dp数组如何初始化 -再回顾一下dp[i]的定义:爬到第i层楼梯,有dp[i]中方法。 +再回顾一下dp[i]的定义:爬到第i层楼梯,有dp[i]种方法。 那么i为0,dp[i]应该是多少呢,这个可以有很多解释,但基本都是直接奔着答案去解释的。 From dad45d599b9368e7ddeeea9b62bc53bea122fc24 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Wed, 29 Mar 2023 11:34:59 +0800 Subject: [PATCH 004/116] Update --- README.md | 2 +- ...合总和IV(完全背包的排列问题二维迭代理解).md | 145 ------------------ ...一道面试题目,讲一讲递归算法的时间复杂度!.md | 16 +- problems/哈希表理论基础.md | 5 +- 4 files changed, 11 insertions(+), 157 deletions(-) delete mode 100644 problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md diff --git a/README.md b/README.md index a9b2f7ef..f3e5812c 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ 如果你是算法老手,这篇攻略也是复习的最佳资料,如果把每个系列对应的总结篇,快速过一遍,整个算法知识体系以及各种解法就重现脑海了。 -目前「代码随想录」刷题攻略更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,部分难点题目还搭配了20分钟左右的视频讲解**。 +目前「代码随想录」刷题攻略更新了:**200多篇文章,精讲了200道经典算法题目,共60w字的详细图解,大部分题目都搭配了20分钟左右的视频讲解**,视频质量很好,口碑很好,大家可以去看看,视频列表:[代码随想录视频讲解](https://www.bilibili.com/video/BV1fA4y1o715)。 **这里每一篇题解,都是精品,值得仔细琢磨**。 diff --git a/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md b/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md deleted file mode 100644 index 276329c5..00000000 --- a/problems/0377-组合总和IV(完全背包的排列问题二维迭代理解).md +++ /dev/null @@ -1,145 +0,0 @@ -# 完全背包的排列问题模拟 - -#### Problem - -1. 排列问题是完全背包中十分棘手的问题。 -2. 其在迭代过程中需要先迭代背包容量,再迭代物品个数,使得其在代码理解上较难入手。 - -#### Contribution - -本文档以力扣上[组合总和IV](https://leetcode.cn/problems/combination-sum-iv/)为例,提供一个二维dp的代码例子,并提供模拟过程以便于理解 - -#### Code - -```cpp -int combinationSum4(vector& nums, int target) { - // 定义背包容量为target,物品个数为nums.size()的dp数组 - // dp[i][j]表示将第0-i个物品添加入排列中,和为j的排列方式 - vector> dp (nums.size(), vector(target+1,0)); - - // 表示有0,1,...,n个物品可选择的情况下,和为0的选择方法为1:什么都不取 - for(int i = 0; i < nums.size(); i++) dp[i][0] = 1; - - // 必须按列遍历,因为右边数组需要知道左边数组最低部的信息(排列问题) - // 后面的模拟可以更清楚的表现这么操作的原因 - for(int i = 1; i <= target; i++){ - for(int j = 0; j < nums.size(); j++){ - // 只有nums[j]可以取的情况 - if(j == 0){ - if(nums[j] > i) dp[j][i] = 0; - // 如果背包容量放不下 那么此时没有排列方式 - else dp[j][i] = dp[nums.size()-1][i-nums[j]]; - // 如果背包容量放的下 全排列方式为dp[最底层][容量-该物品容量]排列方式后面放一个nums[j] - } - // 有多个nums数可以取 - else{ - // 如果背包容量放不下 那么沿用0-j-1个物品的排列方式 - if(nums[j] > i) dp[j][i] = dp[j-1][i]; - // 如果背包容量放得下 在dp[最底层][容量-该物品容量]排列方式后面放一个nums[j]后面放个nums[j] - // INT_MAX避免溢出 - else if(i >= nums[j] && dp[j-1][i] < INT_MAX - dp[nums.size()-1][i-nums[j]]) - dp[j][i] = dp[j-1][i] + dp[nums.size()-1][i-nums[j]]; - } - } - } - // 打印dp数组 - for(int i = 0; i < nums.size(); i++){ - for(int j = 0; j <= target; j++){ - cout< Date: Wed, 29 Mar 2023 11:52:19 +0800 Subject: [PATCH 005/116] =?UTF-8?q?Update=20=E6=A0=B9=E6=8D=AE=E8=BA=AB?= =?UTF-8?q?=E9=AB=98=E9=87=8D=E5=BB=BA=E9=98=9F=E5=88=97=EF=BC=88vector?= =?UTF-8?q?=E5=8E=9F=E7=90=86=E8=AE=B2=E8=A7=A3=EF=BC=89.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../根据身高重建队列(vector原理讲解).md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/根据身高重建队列(vector原理讲解).md b/problems/根据身高重建队列(vector原理讲解).md index 94d94e38..4f8cab82 100644 --- a/problems/根据身高重建队列(vector原理讲解).md +++ b/problems/根据身高重建队列(vector原理讲解).md @@ -177,6 +177,35 @@ Java: Python: +Rust: + +```rust +// 版本二,使用list(链表) +use std::collections::LinkedList; +impl Solution{ + pub fn reconstruct_queue(mut people: Vec>) -> Vec> { + let mut queue = LinkedList::new(); + people.sort_by(|a, b| { + if a[0] == b[0] { + return a[1].cmp(&b[1]); + } + b[0].cmp(&a[0]) + }); + queue.push_back(people[0].clone()); + for v in people.iter().skip(1) { + if queue.len() > v[1] as usize { + let mut back_link = queue.split_off(v[1] as usize); + queue.push_back(v.clone()); + queue.append(&mut back_link); + } else { + queue.push_back(v.clone()); + } + } + queue.into_iter().collect() + } +} +``` + Go: From 59c86a7023989e3cb3195615f30a0a99e39fa556 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Wed, 29 Mar 2023 18:15:26 +0800 Subject: [PATCH 006/116] =?UTF-8?q?Update=200844.=E6=AF=94=E8=BE=83?= =?UTF-8?q?=E5=90=AB=E9=80=80=E6=A0=BC=E7=9A=84=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0844.比较含退格的字符串.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 6534f18c..40d5caa1 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -535,6 +535,35 @@ function getIndexAfterDel(s: string, startIndex: number): number { } ``` +### Rust + +> 双指针 + +```rust +impl Solution { + pub fn backspace_compare(s: String, t: String) -> bool { + let (s, t) = ( + s.chars().collect::>(), + t.chars().collect::>(), + ); + Self::get_string(s) == Self::get_string(t) + } + + pub fn get_string(mut chars: Vec) -> Vec { + let mut slow = 0; + for i in 0..chars.len() { + if chars[i] == '#' { + slow = (slow as u32).saturating_sub(1) as usize; + } else { + chars[slow] = chars[i]; + slow += 1; + } + } + chars.truncate(slow); + chars + } +} +``` From e4951bc9dba7ebaa5314d41a52b0a5d97b8a6cea Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Wed, 29 Mar 2023 18:34:11 +0800 Subject: [PATCH 007/116] =?UTF-8?q?Update=200844.=E6=AF=94=E8=BE=83?= =?UTF-8?q?=E5=90=AB=E9=80=80=E6=A0=BC=E7=9A=84=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0844.比较含退格的字符串.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 40d5caa1..ac56f6f9 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -565,7 +565,27 @@ impl Solution { } ``` +> 双栈法 +```rust +impl Solution { + pub fn backspace_compare(s: String, t: String) -> bool { + Self::get_string(s) == Self::get_string(t) + } + + pub fn get_string(string: String) -> String { + let mut s = String::new(); + for c in string.chars() { + if c != '#' { + s.push(c); + } else if !s.is_empty() { + s.pop(); + } + } + s + } +} +```

From 7e02650599bd98ef92f017f2838c09c17235a502 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E6=97=A0=E7=BC=BA?= Date: Wed, 29 Mar 2023 20:21:27 +0800 Subject: [PATCH 008/116] =?UTF-8?q?update=20=E4=BD=BF=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=B1=E8=B4=B9=E7=88=AC=E6=A5=BC=E6=A2=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化文档中的语言描述 --- problems/0746.使用最小花费爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index d6b3a177..d7258d45 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -92,7 +92,7 @@ dp[i - 2] 跳到 dp[i] 需要花费 dp[i - 2] + cost[i - 2]。 这里就要说明本题力扣为什么改题意,而且修改题意之后 就清晰很多的原因了。 -新题目描述中明确说了 “你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。” 也就是说 从 到达 第 0 个台阶是不花费的,但从 第0 个台阶 往上跳的话,需要花费 cost[0]。 +新题目描述中明确说了 “你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。” 也就是说 到达 第 0 个台阶是不花费的,但从 第0 个台阶 往上跳的话,需要花费 cost[0]。 所以初始化 dp[0] = 0,dp[1] = 0; From d2811139ae718d265b37653ae9ebfd4f07701c9d Mon Sep 17 00:00:00 2001 From: Jeremy Feng <44312563+jeremy-feng@users.noreply.github.com> Date: Fri, 31 Mar 2023 00:35:33 +0800 Subject: [PATCH 009/116] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E8=83=8C=E5=8C=85.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改错别字 --- problems/背包问题理论基础完全背包.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index d0b2ce0b..f80d4671 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -41,7 +41,7 @@ * [动态规划:关于01背包问题,你该了解这些!](https://programmercarl.com/背包理论基础01背包-1.html) * [动态规划:关于01背包问题,你该了解这些!(滚动数组)](https://programmercarl.com/背包理论基础01背包-2.html) -首先在回顾一下01背包的核心代码 +首先再回顾一下01背包的核心代码 ```cpp for(int i = 0; i < weight.size(); i++) { // 遍历物品 for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量 From 96502b5f09b432ebb87f126fb56db83a5504abb4 Mon Sep 17 00:00:00 2001 From: Jeremy Feng <44312563+jeremy-feng@users.noreply.github.com> Date: Fri, 31 Mar 2023 00:39:08 +0800 Subject: [PATCH 010/116] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E8=83=8C=E5=8C=85.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改错别字 --- problems/背包问题理论基础完全背包.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index f80d4671..e927aa20 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -173,7 +173,7 @@ int main() { 别急,下一篇就是了!哈哈 -最后,**又可以出一道面试题了,就是纯完全背包,要求先用二维dp数组实现,然后再用一维dp数组实现,最后在问,两个for循环的先后是否可以颠倒?为什么?** +最后,**又可以出一道面试题了,就是纯完全背包,要求先用二维dp数组实现,然后再用一维dp数组实现,最后再问,两个for循环的先后是否可以颠倒?为什么?** 这个简单的完全背包问题,估计就可以难住不少候选人了。 From f7988e06dc26ffb93d93f41c8454b4d4504f5828 Mon Sep 17 00:00:00 2001 From: ayao98 <91120769+ayao98@users.noreply.github.com> Date: Fri, 31 Mar 2023 15:50:58 +0800 Subject: [PATCH 011/116] =?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 c++语言部分,函数名和节点命名大小写有错误 --- problems/0104.二叉树的最大深度.md | 34 +++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index b95e39c8..36578fd3 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -50,7 +50,7 @@ 代码如下: ```CPP -int getdepth(treenode* node) +int getdepth(TreeNode* node) ``` 2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。 @@ -76,14 +76,14 @@ return depth; ```CPP class solution { public: - int getdepth(treenode* node) { + int getdepth(TreeNode* node) { if (node == NULL) return 0; int leftdepth = getdepth(node->left); // 左 int rightdepth = getdepth(node->right); // 右 int depth = 1 + max(leftdepth, rightdepth); // 中 return depth; } - int maxdepth(treenode* root) { + int maxDepth(TreeNode* root) { return getdepth(root); } }; @@ -93,9 +93,9 @@ public: ```CPP class solution { public: - int maxdepth(treenode* root) { + int maxDepth(TreeNode* root) { if (root == null) return 0; - return 1 + max(maxdepth(root->left), maxdepth(root->right)); + return 1 + max(maxDepth(root->left), maxDepth(root->right)); } }; @@ -110,7 +110,7 @@ public: class solution { public: int result; - void getdepth(treenode* node, int depth) { + void getdepth(TreeNode* node, int depth) { result = depth > result ? depth : result; // 中 if (node->left == NULL && node->right == NULL) return ; @@ -127,7 +127,7 @@ public: } return ; } - int maxdepth(treenode* root) { + int maxDepth(TreeNode* root) { result = 0; if (root == NULL) return result; getdepth(root, 1); @@ -144,7 +144,7 @@ public: class solution { public: int result; - void getdepth(treenode* node, int depth) { + void getdepth(TreeNode* node, int depth) { result = depth > result ? depth : result; // 中 if (node->left == NULL && node->right == NULL) return ; if (node->left) { // 左 @@ -155,7 +155,7 @@ public: } return ; } - int maxdepth(treenode* root) { + int maxDepth(TreeNode* root) { result = 0; if (root == 0) return result; getdepth(root, 1); @@ -182,16 +182,16 @@ c++代码如下: ```CPP class solution { public: - int maxdepth(treenode* root) { + int maxDepth(TreeNode* root) { if (root == NULL) return 0; int depth = 0; - queue que; + queue que; que.push(root); while(!que.empty()) { int size = que.size(); depth++; // 记录深度 for (int i = 0; i < size; i++) { - treenode* node = que.front(); + TreeNode* node = que.front(); que.pop(); if (node->left) que.push(node->left); if (node->right) que.push(node->right); @@ -230,11 +230,11 @@ c++代码: ```CPP class solution { public: - int maxdepth(node* root) { + int maxDepth(Node* root) { if (root == 0) return 0; int depth = 0; for (int i = 0; i < root->children.size(); i++) { - depth = max (depth, maxdepth(root->children[i])); + depth = max (depth, maxDepth(root->children[i])); } return depth + 1; } @@ -247,15 +247,15 @@ public: ```CPP class solution { public: - int maxdepth(node* root) { - queue que; + int maxDepth(Node* root) { + queue que; if (root != NULL) que.push(root); int depth = 0; while (!que.empty()) { int size = que.size(); depth++; // 记录深度 for (int i = 0; i < size; i++) { - node* node = que.front(); + Node* node = que.front(); que.pop(); for (int j = 0; j < node->children.size(); j++) { if (node->children[j]) que.push(node->children[j]); From 6af02057b674d64c19c733c490ae9090e30e498e Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Fri, 31 Mar 2023 18:04:59 +0800 Subject: [PATCH 012/116] =?UTF-8?q?Update=200435.=E6=97=A0=E9=87=8D?= =?UTF-8?q?=E5=8F=A0=E5=8C=BA=E9=97=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0435.无重叠区间.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 02db2034..37ef819d 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -399,18 +399,20 @@ object Solution { ```Rust impl Solution { pub fn erase_overlap_intervals(intervals: Vec>) -> i32 { - if intervals.len() == 0 { return 0; } - let mut intervals = intervals; - intervals.sort_by(|a, b| a[1].cmp(&b[1])); + if intervals.is_empty() { + return 0; + } + intervals.sort_by_key(|interval| interval[1]); let mut count = 1; let mut end = intervals[0][1]; - for i in 1..intervals.len() { - if end <= intervals[i][0] { - end = intervals[i][1]; + for v in intervals.iter().skip(1) { + if end <= v[0] { + end = v[1]; count += 1; } } - intervals.len() as i32 - count + + (intervals.len() - count) as i32 } } ``` From 2208d96581e13b19e4d41610f259b04ad3a75856 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Fri, 31 Mar 2023 18:37:51 +0800 Subject: [PATCH 013/116] =?UTF-8?q?Update=200763.=E5=88=92=E5=88=86?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E5=8C=BA=E9=97=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0763.划分字母区间.md | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md index ad680ef9..fbcafdc8 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -412,28 +412,22 @@ object Solution { ### Rust ```Rust -use std::collections::HashMap; impl Solution { - fn max (a: usize, b: usize) -> usize { - if a > b { a } else { b } - } pub fn partition_labels(s: String) -> Vec { - let s = s.chars().collect::>(); - let mut hash: HashMap = HashMap::new(); - for i in 0..s.len() { - hash.insert(s[i], i); + let mut hash = vec![0; 26]; + for (i, &c) in s.as_bytes().iter().enumerate() { + hash[(c - b'a') as usize] = i; } - let mut result: Vec = Vec::new(); - let mut left: usize = 0; - let mut right: usize = 0; - for i in 0..s.len() { - right = Self::max(right, hash[&s[i]]); + let mut res = vec![]; + let (mut left, mut right) = (0, 0); + for (i, &c) in s.as_bytes().iter().enumerate() { + right = right.max(hash[(c - b'a') as usize]); if i == right { - result.push((right - left + 1) as i32); + res.push((right - left + 1) as i32); left = i + 1; } } - result + res } } ``` From 24d59de1c0ef5580b122516404ea5b5bdd9c0d44 Mon Sep 17 00:00:00 2001 From: GODVvVZzz <2662446324@qq.com> Date: Fri, 31 Mar 2023 20:59:03 +0800 Subject: [PATCH 014/116] =?UTF-8?q?Modify=20376=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97.md=20=E9=94=99=E5=88=AB=E5=AD=97-=E6=9E=9C->=E4=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 469c19fd..ff388b55 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -89,7 +89,7 @@ ### 情况二:数组首尾两端 -所以本题统计峰值的时候,数组最左面和最右面如果统计呢? +所以本题统计峰值的时候,数组最左面和最右面如何统计呢? 题目中说了,如果只有两个不同的元素,那摆动序列也是 2。 @@ -655,3 +655,4 @@ object Solution { + From 7e80792a63f6d0b63745f2bb5c401b1a749afc1a Mon Sep 17 00:00:00 2001 From: YuZou Date: Fri, 31 Mar 2023 22:20:36 +0800 Subject: [PATCH 015/116] =?UTF-8?q?update=200045.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8FII.md=20=E4=BF=AE=E6=94=B9=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E8=AF=AD=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index c6e4e9b5..2f6e8b67 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -76,11 +76,9 @@ public: for (int i = 0; i < nums.size(); i++) { nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖最远距离下标 if (i == curDistance) { // 遇到当前覆盖最远距离下标 - if (curDistance < nums.size() - 1) { // 如果当前覆盖最远距离下标不是终点 - ans++; // 需要走下一步 - curDistance = nextDistance; // 更新当前覆盖最远距离下标(相当于加油了) - if (nextDistance >= nums.size() - 1) break; // 下一步的覆盖范围已经可以达到终点,结束循环 - } else break; // 当前覆盖最远距到达集合终点,不用做ans++操作了,直接结束 + ans++; // 需要走下一步 + curDistance = nextDistance; // 更新当前覆盖最远距离下标(相当于加油了) + if (nextDistance >= nums.size() - 1) break; // 当前覆盖最远距到达集合终点,不用做ans++操作了,直接结束 } } return ans; From 6943358d8f75b4c189bcedaa5b79d5c0b0a93c2a Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Fri, 31 Mar 2023 21:58:27 -0400 Subject: [PATCH 016/116] =?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 增加 python 迭代法 --- problems/0538.把二叉搜索树转换为累加树.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 29b21840..ad5310e1 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -234,6 +234,26 @@ class Solution: return root ``` +**迭代** +```python +class Solution: + def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: return root + stack = [] + result = [] + cur = root + pre = 0 + while cur or stack: + if cur: + stack.append(cur) + cur = cur.right + else: + cur = stack.pop() + cur.val+= pre + pre = cur.val + cur =cur.left + return root +``` ## Go From ddda474eb4d73d894205cd5845b0c41f1b34226b Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sat, 1 Apr 2023 11:42:50 +0800 Subject: [PATCH 017/116] =?UTF-8?q?Update=200056.=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=8C=BA=E9=97=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0056.合并区间.md | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index 17d2cc0a..d03a590d 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -280,24 +280,22 @@ object Solution { ```Rust impl Solution { - fn max(a: i32, b: i32) -> i32 { - if a > b { a } else { b } - } - - pub fn merge(intervals: Vec>) -> Vec> { - let mut intervals = intervals; - let mut result = Vec::new(); - if intervals.len() == 0 { return result; } - intervals.sort_by(|a, b| a[0].cmp(&b[0])); - result.push(intervals[0].clone()); - for i in 1..intervals.len() { - if result.last_mut().unwrap()[1] >= intervals[i][0] { - result.last_mut().unwrap()[1] = Self::max(result.last_mut().unwrap()[1], intervals[i][1]); + pub fn merge(mut intervals: Vec>) -> Vec> { + let mut res = vec![]; + if intervals.is_empty() { + return res; + } + intervals.sort_by_key(|a| a[0]); + res.push(intervals[0].clone()); + for interval in intervals.into_iter().skip(1) { + let res_last_ele = res.last_mut().unwrap(); + if res_last_ele[1] >= interval[0] { + res_last_ele[1] = interval[1].max(res_last_ele[1]); } else { - result.push(intervals[i].clone()); + res.push(interval); } } - result + res } } ``` From cd1a680c26c25e928b7a56f3e98ce8d00f7e1577 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sat, 1 Apr 2023 12:22:37 +0800 Subject: [PATCH 018/116] =?UTF-8?q?Update=200738.=E5=8D=95=E8=B0=83?= =?UTF-8?q?=E9=80=92=E5=A2=9E=E7=9A=84=E6=95=B0=E5=AD=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0738.单调递增的数字.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index f92652cd..1cf8a0a6 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -280,18 +280,20 @@ object Solution { ```Rust impl Solution { pub fn monotone_increasing_digits(n: i32) -> i32 { - let mut str_num = n.to_string().chars().map(|x| x.to_digit(10).unwrap() as i32).collect::>(); - let mut flag = str_num.len(); - for i in (1..str_num.len()).rev() { - if str_num[i - 1] > str_num[i] { + let mut n_bytes = n.to_string().into_bytes(); + let mut flag = n_bytes.len(); + for i in (1..n_bytes.len()).rev() { + if n_bytes[i - 1] > n_bytes[i] { flag = i; - str_num[i - 1] -= 1; + n_bytes[i - 1] -= 1; } } - for i in flag..str_num.len() { - str_num[i] = 9; + for v in n_bytes.iter_mut().skip(flag) { + *v = 57; } - str_num.iter().fold(0, |acc, x| acc * 10 + x) + n_bytes + .into_iter() + .fold(0, |acc, x| acc * 10 + x as i32 - 48) } } ``` From d7d7e6c733716a7eb516dea3c8b7660e8d0ac9ce Mon Sep 17 00:00:00 2001 From: ray Date: Sat, 1 Apr 2023 20:54:58 +0800 Subject: [PATCH 019/116] =?UTF-8?q?=E4=BF=AE=E6=94=B9=200203.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=20=E5=86=99?= =?UTF-8?q?=E6=B3=95=E6=9B=B4Python=E4=B8=80=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 7e3955a5..b52f16ea 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -316,8 +316,8 @@ class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy_head = ListNode(next=head) #添加一个虚拟节点 cur = dummy_head - while(cur.next!=None): - if(cur.next.val == val): + while cur.next: + if cur.next.val == val: cur.next = cur.next.next #删除cur.next节点 else: cur = cur.next From befa14402bbf12eb147235e190bb775a42169ba9 Mon Sep 17 00:00:00 2001 From: jyu <1025368039@qq.com> Date: Sat, 1 Apr 2023 21:45:43 +0800 Subject: [PATCH 020/116] =?UTF-8?q?=E5=A2=9E=E5=8A=A0151=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=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 | 43 +++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 1b006665..8fa7c77c 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -970,6 +970,49 @@ pub fn remove_extra_spaces(s: &mut Vec) { } } ``` +C: + +```C +// 翻转字符串中指定范围的字符 +void reverse(char* s, int start, int end) { + for (int i = start, j = end; i < j; i++, j--) { + int tmp = s[i]; + s[i] = s[j]; + s[j] = tmp; + } +} + +// 删除字符串两端和中间多余的空格 +void removeExtraSpace(char* s) { + int start = 0; // 指向字符串开头的指针 + int end = strlen(s) - 1; // 指向字符串结尾的指针 + while (s[start] == ' ') start++; // 移动指针 start,直到找到第一个非空格字符 + while (s[end] == ' ') end--; // 移动指针 end,直到找到第一个非空格字符 + int slow = 0; // 指向新字符串的下一个写入位置的指针 + for (int i = start; i <= end; i++) { // 遍历整个字符串 + if (s[i] == ' ' && s[i+1] == ' ') { // 如果当前字符是空格,并且下一个字符也是空格,则跳过 + continue; + } + s[slow] = s[i]; // 否则,将当前字符复制到新字符串的 slow 位置 + slow++; // 将 slow 指针向后移动 + } + s[slow] = '\0'; // 在新字符串的末尾添加一个空字符 +} + +// 翻转字符串中的单词 +char * reverseWords(char * s){ + removeExtraSpace(s); // 先删除字符串两端和中间的多余空格 + reverse(s, 0, strlen(s) - 1); // 翻转整个字符串 + int slow = 0; // 指向每个单词的开头位置的指针 + for (int i = 0; i <= strlen(s); i++) { // 遍历整个字符串 + if (s[i] ==' ' || s[i] == '\0') { // 如果当前字符是空格或空字符,说明一个单词结束了 + reverse(s, slow, i-1); // 翻转单词 + slow = i + 1; // 将 slow 指针指向下一个单词的开头位置 + } + } + return s; // 返回处理后的字符串 +} +```

From c1f17275e5879b94e0dcbc321f9dd434068ce516 Mon Sep 17 00:00:00 2001 From: mercer5 <602502833@qq.com> Date: Sun, 2 Apr 2023 11:40:30 +0800 Subject: [PATCH 021/116] =?UTF-8?q?=E6=B7=BB=E5=8A=A00739=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=E6=B8=A9=E5=BA=A6=20python=20=E7=B2=BE=E7=AE=80?= =?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/0739.每日温度.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index 263a28f4..e521fbc6 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -271,6 +271,7 @@ class Solution { ``` Python: +> 未精简版本 ```python class Solution: @@ -291,6 +292,22 @@ class Solution: return answer ``` +> 精简版本 + +```python +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + # 单调栈 + answer = [0]*len(temperatures) + stack = [] + for i in range(len(temperatures)): + while len(stack)>0 and temperatures[i] > temperatures[stack[-1]]: + answer[stack[-1]] = i - stack[-1] + stack.pop() + stack.append(i) + return answer +``` + Go: > 暴力法 From a490e39206f4fd5d89165bbf0b38f982736e5309 Mon Sep 17 00:00:00 2001 From: mercer5 <602502833@qq.com> Date: Sun, 2 Apr 2023 11:50:29 +0800 Subject: [PATCH 022/116] =?UTF-8?q?=E4=BF=AE=E6=94=B90739=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=E6=B8=A9=E5=BA=A6=20python=20=E7=B2=BE=E7=AE=80?= =?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/0739.每日温度.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index e521fbc6..749dc972 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -297,7 +297,6 @@ class Solution: ```python class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: - # 单调栈 answer = [0]*len(temperatures) stack = [] for i in range(len(temperatures)): From 34e1b0ab5ce4a839ac9bf40b9e7ceb582fd51119 Mon Sep 17 00:00:00 2001 From: ayao98 <91120769+ayao98@users.noreply.github.com> Date: Mon, 3 Apr 2023 15:48:51 +0800 Subject: [PATCH 023/116] =?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 --- problems/0112.路径总和.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 9b6027d1..5958de93 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -250,7 +250,7 @@ private: vector> result; vector path; // 递归函数不需要返回值,因为我们要遍历整个树 - void traversal(treenode* cur, int count) { + void traversal(TreeNode* cur, int count) { if (!cur->left && !cur->right && count == 0) { // 遇到了叶子节点且找到了和为sum的路径 result.push_back(path); return; @@ -276,10 +276,10 @@ private: } public: - vector> pathsum(treenode* root, int sum) { + vector> pathSum(TreeNode* root, int sum) { result.clear(); path.clear(); - if (root == null) return result; + if (root == NULL) return result; path.push_back(root->val); // 把根节点放进路径 traversal(root, sum - root->val); return result; From 9e27f3dd9b40dabef0afd7e085fb6dec0e745474 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Tue, 4 Apr 2023 22:51:45 -0400 Subject: [PATCH 024/116] =?UTF-8?q?Update=200332.=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加: python - 使用used数组 - 神似之前几题写法 --- problems/0332.重新安排行程.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 9bd5df7a..95e7d3ed 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -380,7 +380,33 @@ class Solution: backtracking("JFK") return path ``` + +python - 使用used数组 - 神似之前几题写法 +```python +class Solution: + def findItinerary(self, tickets: List[List[str]]) -> List[str]: + global used,path,results + used = [0]*len(tickets) + path = ['JFK'] + results = [] + tickets.sort() # 先排序,这样一旦找到第一个可行路径,一定是字母排序最小的 + self.backtracking(tickets,'JFK') + return results[0] + def backtracking(self,tickets,cur): + if sum(used) == len(tickets): + results.append(path[:]) + return True # 只要找到就返回 + for i in range(len(tickets)): + if tickets[i][0]==cur and used[i]==0: + used[i]=1 + path.append(tickets[i][1]) + state = self.backtracking(tickets,tickets[i][1]) + path.pop() + used[i]=0 + if state: return True # 只要找到就返回,不继续搜索了 +``` + ### GO ```go type pair struct { From 700b5c388bb1c3cb0a0d70ee9d0e0b54d5235a6e Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Thu, 6 Apr 2023 15:48:47 -0400 Subject: [PATCH 025/116] =?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 增加python - 贪心版本三 - 类似‘55-跳跃游戏’写法 --- problems/0045.跳跃游戏II.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index c6e4e9b5..d12664ac 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -231,6 +231,21 @@ class Solution: step += 1 return step ``` +```python +# 贪心版本三 - 类似‘55-跳跃游戏’写法 +class Solution: + def jump(self, nums) -> int: + if len(nums)==1: return 0 + i = 0 + count = 0 + cover = 0 + while i<=cover: + for i in range(i,cover+1): + cover = max(nums[i]+i,cover) + if cover>=len(nums)-1: return count+1 + count+=1 + +``` ```python # 动态规划做法 From bf8c539a635ce317ab9dd9598f06ca30bdebb677 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Thu, 6 Apr 2023 23:39:05 -0400 Subject: [PATCH 026/116] =?UTF-8?q?Update=200452.=E7=94=A8=E6=9C=80?= =?UTF-8?q?=E5=B0=91=E6=95=B0=E9=87=8F=E7=9A=84=E7=AE=AD=E5=BC=95=E7=88=86?= =?UTF-8?q?=E6=B0=94=E7=90=83.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加 python 不改变原数组 写法 --- problems/0452.用最少数量的箭引爆气球.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index 53eee25c..67070ba4 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -177,7 +177,23 @@ class Solution: points[i][1] = min(points[i - 1][1], points[i][1]) # 更新重叠气球最小右边界 return result ``` +```python +class Solution: # 不改变原数组 + def findMinArrowShots(self, points: List[List[int]]) -> int: + points.sort(key = lambda x: x[0]) + sl,sr = points[0][0],points[0][1] + count = 1 + for i in points: + if i[0]>sr: + count+=1 + sl,sr = i[0],i[1] + else: + sl = max(sl,i[0]) + sr = min(sr,i[1]) + return count + +``` ### Go ```go func findMinArrowShots(points [][]int) int { From 4b0982e681e72081752843e8df83c0ceec1b543a Mon Sep 17 00:00:00 2001 From: Liu Cheng <32453247+Falldio@users.noreply.github.com> Date: Fri, 7 Apr 2023 14:29:56 +0800 Subject: [PATCH 027/116] =?UTF-8?q?=E6=B7=BB=E5=8A=A00132.=E5=88=86?= =?UTF-8?q?=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2II=E7=9A=84Golang=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/0132.分割回文串II.md | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0132.分割回文串II.md b/problems/0132.分割回文串II.md index eb0e39fb..9b164dfb 100644 --- a/problems/0132.分割回文串II.md +++ b/problems/0132.分割回文串II.md @@ -289,7 +289,45 @@ class Solution: ## Go ```go +func minCut(s string) int { + isValid := make([][]bool, len(s)) + for i := 0; i < len(isValid); i++ { + isValid[i] = make([]bool, len(s)) + isValid[i][i] = true + } + for i := len(s) - 1; i >= 0; i-- { + for j := i + 1; j < len(s); j++ { + if s[i] == s[j] && (isValid[i + 1][j - 1] || j - i == 1) { + isValid[i][j] = true + } + } + } + dp := make([]int, len(s)) + for i := 0; i < len(s); i++ { + dp[i] = math.MaxInt + } + for i := 0; i < len(s); i++ { + if isValid[0][i] { + dp[i] = 0 + continue + } + for j := 0; j < i; j++ { + if isValid[j + 1][i] { + dp[i] = min(dp[i], dp[j] + 1) + } + } + } + return dp[len(s) - 1] +} + +func min(i, j int) int { + if i < j { + return i + } else { + return j + } +} ``` ## JavaScript From dee25873fc8f594dbc0209453399669df5fdf61a Mon Sep 17 00:00:00 2001 From: Levi <3573897471@qq.com> Date: Fri, 7 Apr 2023 17:05:31 +0800 Subject: [PATCH 028/116] =?UTF-8?q?=E8=A1=A5=E5=85=850111.=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?=E4=B8=AD=E7=9A=84=E5=85=B3=E4=BA=8E=E5=89=8D=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86=EF=BC=88=E4=B8=AD=E5=B7=A6=E5=8F=B3=EF=BC=89=E7=9A=84?= =?UTF-8?q?=E4=B8=AD=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index de36c6f2..47569b05 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -170,11 +170,14 @@ class Solution { private: int result; void getdepth(TreeNode* node, int depth) { - if (node->left == NULL && node->right == NULL) { - result = min(depth, result); + // 函数递归终止条件 + if (root == nullptr) { return; } - // 中 只不过中没有处理的逻辑 + // 中,处理逻辑:判断是不是叶子结点 + if (root -> left == nullptr && root->right == nullptr) { + res = min(res, depth); + } if (node->left) { // 左 getdepth(node->left, depth + 1); } @@ -186,7 +189,9 @@ private: public: int minDepth(TreeNode* root) { - if (root == NULL) return 0; + if (root == nullptr) { + return 0; + } result = INT_MAX; getdepth(root, 1); return result; From e68a8a379be1defd7952a0d87fcac4350363de13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8A=B1=E6=97=A0=E7=BC=BA?= Date: Sun, 9 Apr 2023 14:54:51 +0800 Subject: [PATCH 029/116] =?UTF-8?q?update=20=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更正文档错别字 --- problems/0063.不同路径II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 85130ab4..62210420 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -135,7 +135,7 @@ for (int i = 1; i < m; i++) { ![63.不同路径II2](https://code-thinking-1253855093.file.myqcloud.com/pics/20210104114610256.png) -如果这个图看不同,建议在理解一下递归公式,然后照着文章中说的遍历顺序,自己推导一下! +如果这个图看不懂,建议再理解一下递归公式,然后照着文章中说的遍历顺序,自己推导一下! 动规五部分分析完毕,对应C++代码如下: From e1e695e78d3fbba5ebf01fe1be69c6569f9a035a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sun, 9 Apr 2023 23:11:11 +0800 Subject: [PATCH 030/116] =?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 | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 08175058..479b36a0 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -347,26 +347,32 @@ int fib(int n){ ### Rust 动态规划: ```Rust -pub fn fib(n: i32) -> i32 { - let n = n as usize; - let mut dp = vec![0; 31]; - dp[1] = 1; - for i in 2..=n { - dp[i] = dp[i - 1] + dp[i - 2]; +impl Solution { + pub fn fib(n: i32) -> i32 { + if n <= 1 { + return n; + } + let n = n as usize; + let mut dp = vec![0; n + 1]; + dp[1] = 1; + for i in 2..=n { + dp[i] = dp[i - 2] + dp[i - 1]; + } + dp[n] } - dp[n] } ``` 递归实现: ```Rust -pub fn fib(n: i32) -> i32 { - //若n小于等于1,返回n - f n <= 1 { - return n; +impl Solution { + pub fn fib(n: i32) -> i32 { + if n <= 1 { + n + } else { + Self::fib(n - 1) + Self::fib(n - 2) + } } - //否则返回fib(n-1) + fib(n-2) - return fib(n - 1) + fib(n - 2); } ``` From 185f6df9d8dbad3c67724bdaa97b6fa307b5b9e1 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Sun, 9 Apr 2023 17:25:58 -0400 Subject: [PATCH 031/116] =?UTF-8?q?Update=2020210204=E5=8A=A8=E8=A7=84?= =?UTF-8?q?=E5=91=A8=E6=9C=AB=E6=80=BB=E7=BB=93.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改错别字: 原为:先遍历物品,在遍历背包 改为:先遍历物品,再遍历背包 --- problems/周总结/20210204动规周末总结.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/周总结/20210204动规周末总结.md b/problems/周总结/20210204动规周末总结.md index 9a64c152..fb570bd4 100644 --- a/problems/周总结/20210204动规周末总结.md +++ b/problems/周总结/20210204动规周末总结.md @@ -146,7 +146,7 @@ public: **这也体现了刷题顺序的重要性**。 -先遍历背包,在遍历物品: +先遍历背包,再遍历物品: ```CPP // 版本一 @@ -165,7 +165,7 @@ public: }; ``` -先遍历物品,在遍历背包: +先遍历物品,再遍历背包: ```CPP // 版本二 From 2be03e614ddaa09b11b7bae3de7fddd99b959a92 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Sun, 9 Apr 2023 18:07:43 -0400 Subject: [PATCH 032/116] =?UTF-8?q?Update=200139.=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8B=86=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加:python - 和视频中写法一致(和最上面C++写法一致) --- problems/0139.单词拆分.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index edb2c65a..230942ef 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -351,7 +351,17 @@ class Solution: dp[j] = dp[j] or (dp[j - len(word)] and word == s[j - len(word):j]) return dp[len(s)] ``` - +```python +class Solution: # 和视频中写法一致(和最上面C++写法一致) + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + dp = [False]*(len(s)+1) + dp[0]=True + for j in range(1,len(s)+1): + for i in range(j): + word = s[i:j] + if word in wordDict and dp[i]: dp[j]=True + return dp[-1] +``` From 962744515d4e67a417dc0f87ffda90710b974a76 Mon Sep 17 00:00:00 2001 From: "435962415@qq.com" Date: Mon, 10 Apr 2023 11:59:08 +0800 Subject: [PATCH 033/116] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=860188.?= =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3?= =?UTF-8?q?=E6=97=B6=E6=9C=BAIV=E7=9A=84=E8=A7=A3=E6=B3=95=E4=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0188.买卖股票的最佳时机IV.md | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 4fdd7bf4..77d1c961 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -323,6 +323,42 @@ func max(a, b int) int { } ``` +版本二: 三维 dp数组 +```go +func maxProfit(k int, prices []int) int { + length := len(prices) + if length == 0 { + return 0 + } + // [天数][交易次数][是否持有股票] + // 1表示不持有/卖出, 0表示持有/买入 + dp := make([][][]int, length) + for i := 0; i < length; i++ { + dp[i] = make([][]int, k+1) + for j := 0; j <= k; j++ { + dp[i][j] = make([]int, 2) + } + } + for j := 0; j <= k; j++ { + dp[0][j][0] = -prices[0] + } + for i := 1; i < length; i++ { + for j := 1; j <= k; j++ { + dp[i][j][0] = max188(dp[i-1][j][0], dp[i-1][j-1][1]-prices[i]) + dp[i][j][1] = max188(dp[i-1][j][1], dp[i-1][j][0]+prices[i]) + } + } + return dp[length-1][k][1] +} + +func max188(a, b int) int { + if a > b { + return a + } + return b +} +``` + Javascript: ```javascript From 801e03ab3112da8e3e1666fafded4aa998836723 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Mon, 10 Apr 2023 00:48:03 -0400 Subject: [PATCH 034/116] =?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 增加python - 二维dp数组写法 --- problems/0198.打家劫舍.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index fdb2dabf..20e18c08 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -150,7 +150,17 @@ class Solution: dp[i] = max(dp[i-2]+nums[i], dp[i-1]) return dp[-1] ``` - +```python +class Solution: # 二维dp数组写法 + def rob(self, nums: List[int]) -> int: + dp = [[0,0] for _ in range(len(nums))] + dp[0][1] = nums[0] + for i in range(1,len(nums)): + dp[i][0] = max(dp[i-1][1],dp[i-1][0]) + dp[i][1] = dp[i-1][0]+nums[i] + print(dp) + return max(dp[-1]) +``` Go: ```Go func rob(nums []int) int { From 34aabac5b93af8dcb2e56a48c8f1b9049f2a28be Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Mon, 10 Apr 2023 00:58:56 -0400 Subject: [PATCH 035/116] =?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 增加python - 二维dp数组写法 --- problems/0213.打家劫舍II.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 0627eedb..5d315d5c 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -142,7 +142,20 @@ class Solution: dp[i]=max(dp[i-1],dp[i-2]+nums[i]) return dp[-1] ``` - +```python +class Solution: # 二维dp数组写法 + def rob(self, nums: List[int]) -> int: + if len(nums)<3: return max(nums) + return max(self.default(nums[:-1]),self.default(nums[1:])) + def default(self,nums): + dp = [[0,0] for _ in range(len(nums))] + dp[0][1] = nums[0] + for i in range(1,len(nums)): + dp[i][0] = max(dp[i-1]) + dp[i][1] = dp[i-1][0] + nums[i] + return max(dp[-1]) + +``` Go: ```go From abbcbe1ed0b52b7232957bf9152ad0e92104114d Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 10 Apr 2023 15:28:58 +0800 Subject: [PATCH 036/116] =?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 | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index a06ee91e..c46e3b46 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -470,6 +470,23 @@ impl Solution { } ``` +dp 数组 + +```rust +impl Solution { + pub fn climb_stairs(n: i32) -> i32 { + let n = n as usize; + let mut dp = vec![0; n + 1]; + dp[0] = 1; + dp[1] = 1; + for i in 2..=n { + dp[i] = dp[i - 1] + dp[i - 2]; + } + dp[n] + } +} +``` +

From 03f037afebff9684e9d64283b1d8d5ec690e684a Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Mon, 10 Apr 2023 15:36:23 +0800 Subject: [PATCH 037/116] =?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 | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index c46e3b46..793d3e67 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -454,19 +454,16 @@ public class Solution { ```rust impl Solution { pub fn climb_stairs(n: i32) -> i32 { - if n <= 2 { + if n <= 1 { return n; } - let mut a = 1; - let mut b = 2; - let mut f = 0; - for i in 2..n { + let (mut a, mut b, mut f) = (1, 1, 0); + for _ in 2..=n { f = a + b; a = b; b = f; } - return f; - } + f } ``` From dbcec85e977fce41e5459ef3d108b29abc98883b Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:22:10 +0800 Subject: [PATCH 038/116] =?UTF-8?q?update=200455.=E5=88=86=E5=8F=91?= =?UTF-8?q?=E9=A5=BC=E5=B9=B2=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 3688b3fd..efadb433 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -56,8 +56,6 @@ C++代码整体如下: ```CPP // 版本一 -// 时间复杂度:O(nlogn) -// 空间复杂度:O(1) class Solution { public: int findContentChildren(vector& g, vector& s) { @@ -75,6 +73,9 @@ public: } }; ``` +* 时间复杂度:O(nlogn) +* 空间复杂度:O(1) + 从代码中可以看出我用了一个 index 来控制饼干数组的遍历,遍历饼干并没有再起一个 for 循环,而是采用自减的方式,这也是常用的技巧。 @@ -118,6 +119,9 @@ public: } }; ``` +* 时间复杂度:O(nlogn) +* 空间复杂度:O(1) + 细心的录友可以发现,这种写法,两个循环的顺序改变了,先遍历的饼干,在遍历的胃口,这是因为遍历顺序变了,我们是从小到大遍历。 From 80006ad61592e0268fd4a8857a8a8b687278c5b3 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:28:09 +0800 Subject: [PATCH 039/116] =?UTF-8?q?update=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 1de68041..48f8be29 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -24,8 +24,6 @@ 暴力解法的思路,第一层 for 就是设置起始位置,第二层 for 循环遍历数组寻找最大值 -- 时间复杂度:O(n^2) -- 空间复杂度:O(1) ```CPP class Solution { @@ -44,6 +42,9 @@ public: } }; ``` +* 时间复杂度:O(n^2) +* 空间复杂度:O(1) + 以上暴力的解法 C++勉强可以过,其他语言就不确定了。 @@ -98,7 +99,6 @@ public: } }; ``` - - 时间复杂度:O(n) - 空间复杂度:O(1) From 85f54a718d022e6a3cb5883fb3d9aff5745a3362 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:30:07 +0800 Subject: [PATCH 040/116] =?UTF-8?q?update=20=20=200055.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8F=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0055.跳跃游戏.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index ce9a21ec..c187ef8f 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -75,6 +75,10 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(1) + + ## 总结 这道题目关键点在于:不用拘泥于每次究竟跳几步,而是看覆盖范围,覆盖范围内一定是可以跳过来的,不用管是怎么跳的。 From 4afa9c2a51f3745b1dc6497fd522a607f3174136 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:32:31 +0800 Subject: [PATCH 041/116] =?UTF-8?q?update=20=20=200045.=E8=B7=B3=E8=B7=83?= =?UTF-8?q?=E6=B8=B8=E6=88=8FII=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index c6e4e9b5..558b32b9 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -88,6 +88,10 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(1) + + ## 方法二 依然是贪心,思路和方法一差不多,代码可以简洁一些。 @@ -127,6 +131,11 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(1) + + + 可以看出版本二的代码相对于版本一简化了不少! **其精髓在于控制移动下标 i 只移动到 nums.size() - 2 的位置**,所以移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不用考虑别的了。 From 38c74c90d793b9637feceec6350e269d9e460a16 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:34:25 +0800 Subject: [PATCH 042/116] =?UTF-8?q?update=20=20=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=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1005.K次取反后最大化的数组和.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 4a080857..27a575c7 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -85,6 +85,10 @@ public: }; ``` +* 时间复杂度: O(nlogn) +* 空间复杂度: O(1) + + ## 总结 贪心的题目如果简单起来,会让人简单到开始怀疑:本来不就应该这么做么?这也算是算法?我认为这不是贪心? From 25bf0859a1e7b68ddfcb83456e9828244e0ee703 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:36:37 +0800 Subject: [PATCH 043/116] =?UTF-8?q?update=20=20=200135.=E5=88=86=E5=8F=91?= =?UTF-8?q?=E7=B3=96=E6=9E=9C=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0135.分发糖果.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index ef79868a..1ba1563f 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -121,6 +121,11 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(n) + + + ## 总结 这在leetcode上是一道困难的题目,其难点就在于贪心的策略,如果在考虑局部的时候想两边兼顾,就会顾此失彼。 From 4c7464fa93ca388699b37935e5b56e68b1f6fed2 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:37:48 +0800 Subject: [PATCH 044/116] =?UTF-8?q?update=20=200860.=E6=9F=A0=E6=AA=AC?= =?UTF-8?q?=E6=B0=B4=E6=89=BE=E9=9B=B6=20=EF=BC=9A=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0860.柠檬水找零.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index cd52adb0..d96e0879 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -115,6 +115,9 @@ public: } }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(1) + ## 总结 From ff77937816b26b6aa88a41fb6b1684837ca1a31d Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:41:40 +0800 Subject: [PATCH 045/116] =?UTF-8?q?update=20=20=200056.=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0056.合并区间.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index ec659108..72dc69c5 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -73,6 +73,10 @@ public: }; ``` +* 时间复杂度: O(nlogn) +* 空间复杂度: O(logn),排序需要的空间开销 + + ## 其他语言版本 From 528c1d4f9e9678b143706178f76d91c0de6947c4 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 00:49:38 +0800 Subject: [PATCH 046/116] =?UTF-8?q?update=20=20=200968.=E7=9B=91=E6=8E=A7?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0968.监控二叉树.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 267e7f6e..fdec56ca 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -303,6 +303,11 @@ public: ``` +* 时间复杂度: O(n),需要遍历二叉树上的每个节点 +* 空间复杂度: O(n) + + + 大家可能会惊讶,居然可以这么简短,**其实就是在版本一的基础上,使用else把一些情况直接覆盖掉了**。 在网上关于这道题解可以搜到很多这种神级别的代码,但都没讲不清楚,如果直接看代码的话,指定越看越晕,**所以建议大家对着版本一的代码一步一步来,版本二中看不中用!**。 From 4e1590e26db6363af09e0feef0109d27d48b3958 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:14:10 +0800 Subject: [PATCH 047/116] =?UTF-8?q?update=20=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0474.一和零.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 8d79d701..6a178a25 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -156,6 +156,11 @@ public: }; ``` +* 时间复杂度: O(kmn),k 为strs的长度 +* 空间复杂度: O(mn) + + + ## 总结 不少同学刷过这道题,可能没有总结这究竟是什么背包。 From f701133a9a8b418904cf02583e90d3c7fcbdd743 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:17:04 +0800 Subject: [PATCH 048/116] =?UTF-8?q?update=20=20=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2II=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0518.零钱兑换II.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index eb5a844c..c208754f 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -179,6 +179,11 @@ public: } }; ``` + +* 时间复杂度: O(mn),其中 m 是amount,n 是 coins 的长度 +* 空间复杂度: O(m) + + 是不是发现代码如此精简,哈哈 ## 总结 From 6e62049cd3f06e5bf156240087d90bdfb5910569 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:20:07 +0800 Subject: [PATCH 049/116] =?UTF-8?q?update=20=200377.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=E2=85=A3=20=EF=BC=9A=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0377.组合总和Ⅳ.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index f2287188..ee659723 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -130,6 +130,11 @@ public: ``` +* 时间复杂度: O(target * n),其中 n 为 nums 的长度 +* 空间复杂度: O(target) + + + C++测试用例有两个数相加超过int的数据,所以需要在if里加上dp[i] < INT_MAX - dp[i - num]。 但java就不用考虑这个限制,java里的int也是四个字节吧,也有可能leetcode后台对不同语言的测试数据不一样。 From 84b84e5bf11158c3ab4ac2356c8290060b7ebf45 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:46:51 +0800 Subject: [PATCH 050/116] =?UTF-8?q?update=20=20=200070.=E7=88=AC=E6=A5=BC?= =?UTF-8?q?=E6=A2=AF=E5=AE=8C=E5=85=A8=E8=83=8C=E5=8C=85=E7=89=88=E6=9C=AC?= =?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86?= =?UTF-8?q?=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯完全背包版本.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index 41c2e616..8f8bc9a6 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -101,6 +101,11 @@ public: }; ``` +* 时间复杂度: O(nm) +* 空间复杂度: O(n) + + + 代码中m表示最多可以爬m个台阶,代码中把m改成2就是本题70.爬楼梯可以AC的代码了。 ## 总结 From 9fef5cbd00bde88126d4407c913d4b5f448d5308 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:51:41 +0800 Subject: [PATCH 051/116] =?UTF-8?q?=20update=20=20=200322.=E9=9B=B6?= =?UTF-8?q?=E9=92=B1=E5=85=91=E6=8D=A2=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0322.零钱兑换.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index 3be72565..0e3947da 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -133,6 +133,11 @@ public: }; ``` +* 时间复杂度: O(n * amount),其中 n 为 coins 的长度 +* 空间复杂度: O(amount) + + + 对于遍历方式遍历背包放在外循环,遍历物品放在内循环也是可以的,我就直接给出代码了 ```CPP @@ -154,6 +159,8 @@ public: } }; ``` +* 同上 + ## 总结 From b6fcdc160d85cd5d541c851f514e7ea332ffd4b4 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 11:57:47 +0800 Subject: [PATCH 052/116] =?UTF-8?q?=20update=20=20=200279.=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E5=B9=B3=E6=96=B9=E6=95=B0=EF=BC=9A=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0279.完全平方数.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index c329156b..f5b23d26 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -127,6 +127,10 @@ public: }; ``` +* 时间复杂度: O(n * √n) +* 空间复杂度: O(n) + + 同样我在给出先遍历物品,在遍历背包的代码,一样的可以AC的。 ```CPP @@ -145,6 +149,8 @@ public: } }; ``` +* 同上 + ## 总结 From ecf8251c6ad8c3524ebbe282a62a682acc91824b Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 13:58:53 +0800 Subject: [PATCH 053/116] =?UTF-8?q?update=20=20=200198.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8D=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0198.打家劫舍.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index fdb2dabf..c25f3b86 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -108,6 +108,9 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(n) + ## 总结 打家劫舍是DP解决的经典题目,这道题也是打家劫舍入门级题目,后面我们还会变种方式来打劫的。 From 6754a955688dd80870593da89fa26d889074e748 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:00:01 +0800 Subject: [PATCH 054/116] =?UTF-8?q?update=20=200213.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8DII=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0213.打家劫舍II.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 0627eedb..becad069 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -82,6 +82,11 @@ public: }; ``` +* 时间复杂度: O(n) +* 空间复杂度: O(n) + + + ## 总结 成环之后还是难了一些的, 不少题解没有把“考虑房间”和“偷房间”说清楚。 From 56b35274356fe0cecda151e5d1aa77a9f8b750b3 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:07:01 +0800 Subject: [PATCH 055/116] =?UTF-8?q?update=20=200188.=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?IV=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6?= =?UTF-8?q?=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0188.买卖股票的最佳时机IV.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 4fdd7bf4..f6744a2b 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -156,6 +156,11 @@ public: }; ``` +* 时间复杂度: O(n * k),其中 n 为 prices 的长度 +* 空间复杂度: O(n * k) + + + 当然有的解法是定义一个三维数组dp[i][j][k],第i天,第j次买卖,k表示买还是卖的状态,从定义上来讲是比较直观。 但感觉三维数组操作起来有些麻烦,我是直接用二维数组来模拟三维数组的情况,代码看起来也清爽一些。 From 5bc0fa5c96684068bec235ca353e297b199f5414 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:08:42 +0800 Subject: [PATCH 056/116] =?UTF-8?q?=20update=20=20=200300.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97=EF=BC=9A?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0300.最长上升子序列.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 478837cc..e8cb0b5f 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -106,6 +106,10 @@ public: } }; ``` +* 时间复杂度: O(n^2) +* 空间复杂度: O(n) + + ## 总结 From 1ed179e233bc18574a3f4e7b46cbbed9ab686667 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:11:04 +0800 Subject: [PATCH 057/116] =?UTF-8?q?update=20=20=201143.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E5=AD=90=E5=BA=8F=E5=88=97=EF=BC=9A=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1143.最长公共子序列.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index 8e5f7eb2..730e9ad1 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -124,6 +124,10 @@ public: } }; ``` +* 时间复杂度: O(n * m),其中 n 和 m 分别为 text1 和 text2 的长度 +* 空间复杂度: O(n * m) + + ## 其他语言版本 From 4ded4b5c820f3098ab54a3dbd6cda23e0c5e70ff Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:12:41 +0800 Subject: [PATCH 058/116] =?UTF-8?q?update=20=20=201035.=E4=B8=8D=E7=9B=B8?= =?UTF-8?q?=E4=BA=A4=E7=9A=84=E7=BA=BF=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1035.不相交的线.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/1035.不相交的线.md b/problems/1035.不相交的线.md index d1e1e30a..7b60abdd 100644 --- a/problems/1035.不相交的线.md +++ b/problems/1035.不相交的线.md @@ -62,6 +62,10 @@ public: } }; ``` +* 时间复杂度: O(n * m) +* 空间复杂度: O(n * m) + + ## 总结 From f579a9f82e89f18338b7af64f94e76a63fa7f96d Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:14:03 +0800 Subject: [PATCH 059/116] =?UTF-8?q?update=20=20=200115.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E7=9A=84=E5=AD=90=E5=BA=8F=E5=88=97=EF=BC=9A=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0115.不同的子序列.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0115.不同的子序列.md b/problems/0115.不同的子序列.md index daa708bc..6127f190 100644 --- a/problems/0115.不同的子序列.md +++ b/problems/0115.不同的子序列.md @@ -149,6 +149,11 @@ public: }; ``` +* 时间复杂度: O(n * m) +* 空间复杂度: O(n * m) + + + ## 其他语言版本 From 7d6476c16a421ef03c56ee101e1fd16b1d47ea9c Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:15:40 +0800 Subject: [PATCH 060/116] =?UTF-8?q?update=20=200583.=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=88=A0=E9=99=A4=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=20=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0583.两个字符串的删除操作.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index eb046a9d..561ad2f2 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -104,6 +104,10 @@ public: }; ``` +* 时间复杂度: O(n * m) +* 空间复杂度: O(n * m) + + ### 动态规划二 @@ -127,6 +131,10 @@ public: }; ``` +* 时间复杂度: O(n * m) +* 空间复杂度: O(n * m) + + ## 其他语言版本 From 541ac6ef3cfe7da2312df2cedf9df63edce2b325 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:16:43 +0800 Subject: [PATCH 061/116] =?UTF-8?q?update=20=20=200072.=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E8=B7=9D=E7=A6=BB=EF=BC=9A=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0072.编辑距离.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 0b49e3c6..cc4ab00c 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -218,6 +218,10 @@ public: } }; ``` +* 时间复杂度: O(n * m) +* 空间复杂度: O(n * m) + + ## 其他语言版本 From a26fe0fdf4559c535ac3f04d4e43e87b86b01196 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Tue, 11 Apr 2023 14:17:50 +0800 Subject: [PATCH 062/116] =?UTF-8?q?update=20=200516.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E5=BA=8F=E5=88=97=20=EF=BC=9A?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0516.最长回文子序列.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md index d28a33cc..fcdd57b0 100644 --- a/problems/0516.最长回文子序列.md +++ b/problems/0516.最长回文子序列.md @@ -144,6 +144,11 @@ public: } }; ``` +* 时间复杂度: O(n^2) +* 空间复杂度: O(n^2) + + + ## 其他语言版本 From 8f58ab445a4f7a50a0a9d3ab9c2041dba0c1f2d9 Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 20:20:33 +0800 Subject: [PATCH 063/116] =?UTF-8?q?=E6=9B=B4=E6=96=B0242.=E6=9C=89?= =?UTF-8?q?=E6=95=88=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D=E8=AF=8D?= =?UTF-8?q?=EF=BC=8Cjs=E6=96=B9=E6=B3=95=EF=BC=8C=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1006ea35..ba802bbd 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -205,6 +205,19 @@ var isAnagram = function(s, t) { } return true; }; + +var isAnagram = function(s, t) { + if(s.length !== t.length) return false; + let char_count = new Map(); + for(let item of s) { + char_count.set(item, (char_count.get(item) || 0) + 1) ; + } + for(let item of t) { + if(!char_count.get(item)) return false; + char_count.set(item, char_count.get(item)-1); + } + return true; +}; ``` TypeScript: From eef44eb9e82c6f8c605e4e2575a3200dafe0014d Mon Sep 17 00:00:00 2001 From: Erincrying <1016158928@qq.com> Date: Tue, 11 Apr 2023 21:26:44 +0800 Subject: [PATCH 064/116] =?UTF-8?q?=E6=9B=B4=E6=96=B01002.=20=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6=EF=BC=8Cjs?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E9=87=87=E7=94=A8map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index fd188660..9ec3c6c4 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -252,6 +252,36 @@ var commonChars = function (words) { } return res }; + +// 方法二:map() +var commonChars = function(words) { + let min_count = new Map() + // 统计字符串中字符出现的最小频率,以第一个字符串初始化 + for(let str of words[0]) { + min_count.set(str, ((min_count.get(str) || 0) + 1)) + } + // 从第二个单词开始统计字符出现次数 + for(let i = 1; i < words.length; i++) { + let char_count = new Map() + for(let str of words[i]) { // 遍历字母 + char_count.set(str, (char_count.get(str) || 0) + 1) + } + // 比较出最小的字符次数 + for(let value of min_count) { // 注意这里遍历min_count!而不是单词 + min_count.set(value[0], Math.min((min_count.get(value[0]) || 0), (char_count.get(value[0]) || 0))) + } + } + // 遍历map + let res = [] + min_count.forEach((value, key) => { + if(value) { + for(let i=0; i Date: Thu, 13 Apr 2023 12:20:18 +0800 Subject: [PATCH 065/116] =?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 | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index d7258d45..98a58c12 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -351,17 +351,29 @@ function minCostClimbingStairs(cost: number[]): number { ### Rust ```Rust -use std::cmp::min; impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { - let len = cost.len(); - let mut dp = vec![0; len]; - dp[0] = cost[0]; - dp[1] = cost[1]; - for i in 2..len { - dp[i] = min(dp[i-1], dp[i-2]) + cost[i]; + let mut dp = vec![0; cost.len() + 1]; + for i in 2..=cost.len() { + dp[i] = (dp[i - 1] + cost[i - 1]).min(dp[i - 2] + cost[i - 2]); } - min(dp[len-1], dp[len-2]) + dp[cost.len()] + } +} +``` + +不使用 dp 数组 + +```rust +impl Solution { + pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { + let (mut dp_before, mut dp_after) = (0, 0); + for i in 2..=cost.len() { + let dpi = (dp_before + cost[i - 2]).min(dp_after + cost[i - 1]); + dp_before = dp_after; + dp_after = dpi; + } + dp_after } } ``` From e9c4d54f537a1c42f71b5651bfc4baa0cd1a51e8 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:28:51 +0800 Subject: [PATCH 066/116] =?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 | 37 ++++++++++++++++------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 98a58c12..3d014858 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -330,22 +330,27 @@ var minCostClimbingStairs = function(cost) { ```typescript function minCostClimbingStairs(cost: number[]): number { - /** - dp[i]: 走到第i阶需要花费的最少金钱 - dp[0]: 0; - dp[1]: 0; - ... - dp[i]: min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); - */ - const dp = []; - const length = cost.length; - dp[0] = 0; - dp[1] = 0; - for (let i = 2; i <= length; i++) { - dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); - } - return dp[length]; -}; + const dp = [0, 0] + for (let i = 2; i <= cost.length; i++) { + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + } + return dp[cost.length] +} +``` + +不使用 dp 数组 + +```typescript +function minCostClimbingStairs(cost: number[]): number { + let dp_before = 0, + dp_after = 0 + for (let i = 2; i <= cost.length; i++) { + let dpi = Math.min(dp_before + cost[i - 2], dp_after + cost[i - 1]) + dp_before = dp_after + dp_after = dpi + } + return dp_after +} ``` ### Rust From 1ad26f69cdffc20bec0c95669e929dab0f7d3b2c Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:37:03 +0800 Subject: [PATCH 067/116] =?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 | 41 +++++++++++++++++++---------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 3d014858..fb5261f3 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -312,17 +312,30 @@ func min(a, b int) int { ``` -### Javascript +### JavaScript + ```Javascript var minCostClimbingStairs = function(cost) { - const n = cost.length; - const dp = new Array(n + 1); - dp[0] = dp[1] = 0; - for (let i = 2; i <= n; ++i) { - dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + const dp = [0, 0] + for (let i = 2; i <= cost.length; ++i) { + dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + } + return dp[cost.length] +}; +``` + +不使用 dp 数组 + +```JavaScript +var minCostClimbingStairs = function(cost) { + let dpBefore = 0, + dpAfter = 0 + for(let i = 2;i <= cost.length;i++){ + let dpi = Math.min(dpBefore + cost[i - 2],dpAfter + cost[i - 1]) + dpBefore = dpAfter + dpAfter = dpi } - - return dp[n] + return dpAfter }; ``` @@ -342,14 +355,14 @@ function minCostClimbingStairs(cost: number[]): number { ```typescript function minCostClimbingStairs(cost: number[]): number { - let dp_before = 0, - dp_after = 0 + let dpBefore = 0, + dpAfter = 0 for (let i = 2; i <= cost.length; i++) { - let dpi = Math.min(dp_before + cost[i - 2], dp_after + cost[i - 1]) - dp_before = dp_after - dp_after = dpi + let dpi = Math.min(dpBefore + cost[i - 2], dpAfter + cost[i - 1]) + dpBefore = dpAfter + dpAfter = dpi } - return dp_after + return dpAfter } ``` From ac16522a48d90d45d2f87f50a2c336fc383f4134 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 12:37:46 +0800 Subject: [PATCH 068/116] =?UTF-8?q?Update=20problems/0746.=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=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/0746.使用最小花费爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index fb5261f3..561441fc 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -314,7 +314,7 @@ func min(a, b int) int { ### JavaScript -```Javascript +```JavaScript var minCostClimbingStairs = function(cost) { const dp = [0, 0] for (let i = 2; i <= cost.length; ++i) { From 057d6b8f89ea5bbef1bb460ce40d9093abd1c3e0 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 13:34:46 +0800 Subject: [PATCH 069/116] =?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 | 33 +++++++++++++++++++---------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 561441fc..f11439c0 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -399,18 +399,29 @@ impl Solution { ### C ```c -int minCostClimbingStairs(int* cost, int costSize){ - //开辟dp数组,大小为costSize - int *dp = (int *)malloc(sizeof(int) * costSize); - //初始化dp[0] = cost[0], dp[1] = cost[1] - dp[0] = cost[0], dp[1] = cost[1]; +#include +int minCostClimbingStairs(int *cost, int costSize) { + int dp[costSize + 1]; + dp[0] = dp[1] = 0; + for (int i = 2; i <= costSize; i++) { + dp[i] = fmin(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]); + } + return dp[costSize]; +} +``` - int i; - for(i = 2; i < costSize; ++i) { - dp[i] = (dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]) + cost[i]; - } - //选出倒数2层楼梯中较小的 - return dp[i-1] < dp[i-2] ? dp[i-1] : dp[i-2]; +不使用 dp 数组 + +```c +#include +int minCostClimbingStairs(int *cost, int costSize) { + int dpBefore = 0, dpAfter = 0; + for (int i = 2; i <= costSize; i++) { + int dpi = fmin(dpBefore + cost[i - 2], dpAfter + cost[i - 1]); + dpBefore = dpAfter; + dpAfter = dpi; + } + return dpAfter; } ``` From f7680ab01d27b57e97dfe85796ac7c3c28b06d41 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Thu, 13 Apr 2023 17:01:45 +0800 Subject: [PATCH 070/116] =?UTF-8?q?Update=200062.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0062.不同路径.md | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index bf436369..2ca15726 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -395,21 +395,14 @@ function uniquePaths(m: number, n: number): number { ```Rust impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { - let m = m as usize; - let n = n as usize; - let mut dp = vec![vec![0; n]; m]; - for i in 0..m { - dp[i][0] = 1; + let (m, n) = (m as usize, n as usize); + let mut dp = vec![vec![1; n]; m]; + for i in 1..m { + for j in 1..n { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } - for j in 0..n { - dp[0][j] = 1; - } - for i in 1..m { - for j in 1..n { - dp[i][j] = dp[i-1][j] + dp[i][j-1]; - } - } - dp[m-1][n-1] + } + dp[m - 1][n - 1] } } ``` From 341b0aa672e9ca2d8a5b1cea2bc5ba307e795eda Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 17 Apr 2023 10:37:39 +0800 Subject: [PATCH 071/116] =?UTF-8?q?Update=20problems/0746.=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=9C=80=E5=B0=8F=E8=8A=B1=E8=B4=B9=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/0746.使用最小花费爬楼梯.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index f11439c0..31e7bd48 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -318,7 +318,7 @@ func min(a, b int) int { var minCostClimbingStairs = function(cost) { const dp = [0, 0] for (let i = 2; i <= cost.length; ++i) { - dp[i] = Math.min(dp[i -1] + cost[i - 1], dp[i - 2] + cost[i - 2]) + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) } return dp[cost.length] }; From b7ea55c93b68391ecd87c39c06e2811f0ed6b98f Mon Sep 17 00:00:00 2001 From: Winson Huang Date: Tue, 18 Apr 2023 21:07:54 +0800 Subject: [PATCH 072/116] =?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 修改 Java 语言版本代码,让 HashMap 相关操作更简洁 --- problems/0454.四数相加II.md | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 411b60e8..abfc7c23 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -102,21 +102,14 @@ class Solution { //统计两个数组中的元素之和,同时统计出现的次数,放入map for (int i : nums1) { for (int j : nums2) { - int tmp = map.getOrDefault(i + j, 0); - if (tmp == 0) { - map.put(i + j, 1); - } else { - map.replace(i + j, tmp + 1); - } + int sum = i + j; + map.put(sum, map.getOrDefault(sum, 0) + 1); } } //统计剩余的两个元素的和,在map中找是否存在相加为0的情况,同时记录次数 for (int i : nums3) { for (int j : nums4) { - int tmp = map.getOrDefault(0 - i - j, 0); - if (tmp != 0) { - res += tmp; - } + res += map.getOrDefault(0 - i - j, 0); } } return res; From 747563607292b4fc84452c4f45c2d0504531a171 Mon Sep 17 00:00:00 2001 From: Winson Huang Date: Tue, 18 Apr 2023 21:19:42 +0800 Subject: [PATCH 073/116] =?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 为 Java 语言版本的代码添加长度判断 --- problems/0383.赎金信.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index d9a184b6..a3f87d4a 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -117,6 +117,10 @@ Java: ```Java class Solution { public boolean canConstruct(String ransomNote, String magazine) { + // shortcut + if (ransomNote.length() > magazine.length()) { + return false; + } // 定义一个哈希映射数组 int[] record = new int[26]; From 3f2a816f3096c6ccccba41c81b3975ca80f6d081 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 18 Apr 2023 18:23:24 -0400 Subject: [PATCH 074/116] =?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 新增java 統一迭代法 --- problems/0112.路径总和.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5958de93..b1457887 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -385,6 +385,42 @@ class solution { } } ``` +```Java 統一迭代法 + public boolean hasPathSum(TreeNode root, int targetSum) { + Stack treeNodeStack = new Stack<>(); + Stack sumStack = new Stack<>(); + + if(root == null) + return false; + treeNodeStack.add(root); + sumStack.add(root.val); + + while(!treeNodeStack.isEmpty()){ + TreeNode curr = treeNodeStack.peek(); + int tempsum = sumStack.pop(); + if(curr != null){ + treeNodeStack.pop(); + treeNodeStack.add(curr); + treeNodeStack.add(null); + sumStack.add(tempsum); + if(curr.right != null){ + treeNodeStack.add(curr.right); + sumStack.add(tempsum + curr.right.val); + } + if(curr.left != null){ + treeNodeStack.add(curr.left); + sumStack.add(tempsum + curr.left.val); + } + }else{ + treeNodeStack.pop(); + TreeNode temp = treeNodeStack.pop(); + if(temp.left == null && temp.right == null && tempsum == targetSum) + return true; + } + } + return false; + } +``` ### 0113.路径总和-ii From 0cfe55180439c77995abefaa02c5b61108203f3a Mon Sep 17 00:00:00 2001 From: asxy <17375702582@163.com> Date: Thu, 20 Apr 2023 11:14:43 +0800 Subject: [PATCH 075/116] =?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 回文子串添加java动态规划简单版本的代码 --- problems/0647.回文子串.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 90e6da9f..521c8c26 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -267,6 +267,27 @@ class Solution { return ans; } } + +``` + +动态规划:简洁版 +```java +class Solution { + public int countSubstrings(String s) { + boolean[][] dp = new boolean[s.length()][s.length()]; + + int res = 0; + for (int i = s.length() - 1; i >= 0; i--) { + for (int j = i; j < s.length(); j++) { + if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || dp[i + 1][j - 1])) { + res++; + dp[i][j] = true; + } + } + } + return res; + } +} ``` 中心扩散法: From fca305039005936bc9678c01d7573d6a2f8552ba Mon Sep 17 00:00:00 2001 From: asxy Date: Thu, 20 Apr 2023 11:47:39 +0800 Subject: [PATCH 076/116] =?UTF-8?q?Update=200084.=E6=9F=B1=E7=8A=B6?= =?UTF-8?q?=E5=9B=BE=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84=E7=9F=A9=E5=BD=A2?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加单调栈精简java代码 --- problems/0084.柱状图中最大的矩形.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index eb064143..f9a83508 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -307,6 +307,33 @@ class Solution { } } ``` +单调栈精简 +```java +class Solution { + public int largestRectangleArea(int[] heights) { + int[] newHeight = new int[heights.length + 2]; + System.arraycopy(heights, 0, newHeight, 1, heights.length); + newHeight[heights.length+1] = 0; + newHeight[0] = 0; + + Stack stack = new Stack<>(); + stack.push(0); + + int res = 0; + for (int i = 1; i < newHeight.length; i++) { + while (newHeight[i] < newHeight[stack.peek()]) { + int mid = stack.pop(); + int w = i - stack.peek() - 1; + int h = newHeight[mid]; + res = Math.max(res, w * h); + } + stack.push(i); + + } + return res; + } +} +``` Python3: From f7bdc58b2802e8b81483a5c2f8023499a3d525c4 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 20 Apr 2023 01:18:03 -0500 Subject: [PATCH 077/116] =?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 修改 python 代码,dummy node --- problems/0707.设计链表.md | 71 +++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 33 deletions(-) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 5c78a12a..c72b7327 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -486,15 +486,10 @@ class MyLinkedList { Python: ```python # 单链表 -class Node(object): - def __init__(self, x=0): - self.val = x - self.next = None - -class MyLinkedList(object): +class MyLinkedList1: def __init__(self): - self.head = Node() + self.dummy_head = Node()# 添加虚拟头指针,便于操作 self.size = 0 # 设置一个链表长度的属性,便于后续操作,注意每次增和删的时候都要更新 def get(self, index): @@ -504,7 +499,7 @@ class MyLinkedList(object): """ if index < 0 or index >= self.size: return -1 - cur = self.head.next + cur = self.dummy_head.next while(index): cur = cur.next index -= 1 @@ -516,8 +511,8 @@ class MyLinkedList(object): :rtype: None """ new_node = Node(val) - new_node.next = self.head.next - self.head.next = new_node + new_node.next = self.dummy_head.next + self.dummy_head.next = new_node self.size += 1 def addAtTail(self, val): @@ -526,7 +521,7 @@ class MyLinkedList(object): :rtype: None """ new_node = Node(val) - cur = self.head + cur = self.dummy_head while(cur.next): cur = cur.next cur.next = new_node @@ -548,12 +543,12 @@ class MyLinkedList(object): return node = Node(val) - pre = self.head + cur = self.dummy_head while(index): - pre = pre.next + cur = cur.next index -= 1 - node.next = pre.next - pre.next = node + node.next = cur.next + cur.next = node self.size += 1 def deleteAtIndex(self, index): @@ -563,7 +558,7 @@ class MyLinkedList(object): """ if index < 0 or index >= self.size: return - pre = self.head + pre = self.dummy_head while(index): pre = pre.next index -= 1 @@ -574,11 +569,10 @@ class MyLinkedList(object): # 相对于单链表, Node新增了prev属性 class Node: - def __init__(self, val): + def __init__(self, val=0, next = None, prev = None): self.val = val - self.prev = None - self.next = None - + self.next = next + self.prev = prev class MyLinkedList: @@ -601,6 +595,20 @@ class MyLinkedList: node = node.next return node + + def _update(self, prev: Node, next: Node, val: int) -> None: + """ + 更新节点 + :param prev: 相对于更新的前一个节点 + :param next: 相对于更新的后一个节点 + :param val: 要添加的节点值 + """ + # 计数累加 + self._count += 1 + node = Node(val) + prev.next, next.prev = node, node + node.prev, node.next = prev, next + def get(self, index: int) -> int: """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. @@ -634,19 +642,6 @@ class MyLinkedList: node = self._get_node(index) self._update(node.prev, node, val) - def _update(self, prev: Node, next: Node, val: int) -> None: - """ - 更新节点 - :param prev: 相对于更新的前一个节点 - :param next: 相对于更新的后一个节点 - :param val: 要添加的节点值 - """ - # 计数累加 - self._count += 1 - node = Node(val) - prev.next, next.prev = node, node - node.prev, node.next = prev, next - def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. @@ -656,6 +651,16 @@ class MyLinkedList: # 计数-1 self._count -= 1 node.prev.next, node.next.prev = node.next, node.prev + + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) ``` Go: From 7a41318056f7aa10ef7d4653dd1c3fb988b64448 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Fri, 21 Apr 2023 22:27:05 +0800 Subject: [PATCH 078/116] Update --- problems/0047.全排列II.md | 13 +++++++++++++ problems/0055.跳跃游戏.md | 2 +- problems/0056.合并区间.md | 1 - problems/0112.路径总和.md | 2 +- problems/0455.分发饼干.md | 2 +- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index b4f7a4d8..b1908fb4 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -158,6 +158,19 @@ if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) { 所以我通过举[1,1,1]的例子,把这两个去重的逻辑分别抽象成树形结构,大家可以一目了然:为什么两种写法都可以以及哪一种效率更高! +这里可能大家又有疑惑,既然 `used[i - 1] == false`也行而`used[i - 1] == true`也行,那为什么还要写这个条件呢? + +直接这样写 不就完事了? + +```cpp +if (i > 0 && nums[i] == nums[i - 1]) { + continue; +} +``` + +其实并不行,一定要加上 `used[i - 1] == false`或者`used[i - 1] == true`,因为 used[i - 1] 要一直是 true 或者一直是false 才可以,而不是 一会是true 一会又是false。 所以这个条件要写上。 + + 是不是豁然开朗了!! ## 其他语言版本 diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index a898263d..fa76bc27 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -46,8 +46,8 @@ 如图: +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230203105634.png) -![55.跳跃游戏](https://code-thinking-1253855093.file.myqcloud.com/pics/20201124154758229-20230310135019977.png) i每次移动只能在cover的范围内移动,每移动一个元素,cover得到该元素数值(新的覆盖范围)的补充,让i继续移动下去。 diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index d467ab1a..08a3cb31 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -106,7 +106,6 @@ class Solution { } } -} ``` ```java // 版本2 diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index e412d38e..43a623b5 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -17,7 +17,7 @@ 示例: 给定如下二叉树,以及目标和 sum = 22, -![112.路径总和1](https://img-blog.csdnimg.cn/20210203160355234.png) +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230407210247.png) 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 63525b03..e525175b 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -44,7 +44,7 @@ 如图: -![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230203105634.png) +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230405225628.png) 这个例子可以看出饼干9只有喂给胃口为7的小孩,这样才是整体最优解,并想不出反例,那么就可以撸代码了。 From 252e330a6b20fa13e81e4412c91f40547e0ba1b1 Mon Sep 17 00:00:00 2001 From: HOUSHENGREN <48871516+HOUSHENGREN@users.noreply.github.com> Date: Sun, 23 Apr 2023 14:36:27 +0800 Subject: [PATCH 079/116] =?UTF-8?q?Update=20=E5=88=B7=E5=8A=9B=E6=89=A3?= =?UTF-8?q?=E7=94=A8=E4=B8=8D=E7=94=A8=E5=BA=93=E5=87=BD=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix:文字错误 --- problems/前序/刷力扣用不用库函数.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/刷力扣用不用库函数.md b/problems/前序/刷力扣用不用库函数.md index ae0940bf..04fce856 100644 --- a/problems/前序/刷力扣用不用库函数.md +++ b/problems/前序/刷力扣用不用库函数.md @@ -24,5 +24,5 @@ 例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是O(n^2)的时间复杂度了。 -在刷题的时候本着我说的标准来使用库函数,详细对大家回有所帮助! +在刷题的时候本着我说的标准来使用库函数,相信对大家回有所帮助! From b8f6df60c432fd85d9417e0ce138a90b4603527e Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Sun, 23 Apr 2023 02:40:34 -0400 Subject: [PATCH 080/116] =?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 新增一java寫法 和卡哥的思路一樣的 --- .../0106.从中序与后序遍历序列构造二叉树.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index adb374f9..8fc973e0 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -622,7 +622,42 @@ class Solution { } } ``` +```java +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + if(postorder.length == 0 || inorder.length == 0) + return null; + return buildHelper(inorder, 0, inorder.length, postorder, 0, postorder.length); + + } + private TreeNode buildHelper(int[] inorder, int inorderStart, int inorderEnd, int[] postorder, int postorderStart, int postorderEnd){ + if(postorderStart == postorderEnd) + return null; + int rootVal = postorder[postorderEnd - 1]; + TreeNode root = new TreeNode(rootVal); + int middleIndex; + for (middleIndex = inorderStart; middleIndex < inorderEnd; middleIndex++){ + if(inorder[middleIndex] == rootVal) + break; + } + int leftInorderStart = inorderStart; + int leftInorderEnd = middleIndex; + int rightInorderStart = middleIndex + 1; + int rightInorderEnd = inorderEnd; + + + int leftPostorderStart = postorderStart; + int leftPostorderEnd = postorderStart + (middleIndex - inorderStart); + int rightPostorderStart = leftPostorderEnd; + int rightPostorderEnd = postorderEnd - 1; + root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart, leftPostorderEnd); + root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart, rightPostorderEnd); + + return root; + } +} +``` 105.从前序与中序遍历序列构造二叉树 ```java From f17c74ceec294a90f864a1a9a3836a03b4a752bb Mon Sep 17 00:00:00 2001 From: HOUSHENGREN <48871516+HOUSHENGREN@users.noreply.github.com> Date: Sun, 23 Apr 2023 15:14:25 +0800 Subject: [PATCH 081/116] =?UTF-8?q?Update=20=E5=88=B7=E5=8A=9B=E6=89=A3?= =?UTF-8?q?=E7=94=A8=E4=B8=8D=E7=94=A8=E5=BA=93=E5=87=BD=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat:修改文案 --- problems/前序/刷力扣用不用库函数.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/刷力扣用不用库函数.md b/problems/前序/刷力扣用不用库函数.md index 04fce856..7d0e3475 100644 --- a/problems/前序/刷力扣用不用库函数.md +++ b/problems/前序/刷力扣用不用库函数.md @@ -24,5 +24,5 @@ 例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是O(n^2)的时间复杂度了。 -在刷题的时候本着我说的标准来使用库函数,相信对大家回有所帮助! +在刷题的时候本着我说的标准来使用库函数,相信对大家会有所帮助! From dd290cf33ba44e857021985197122a2982d76874 Mon Sep 17 00:00:00 2001 From: Binbin Date: Mon, 24 Apr 2023 14:28:47 +0800 Subject: [PATCH 082/116] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200104.=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?.md=20=E9=87=8C=E7=9A=84=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后者 -> 或者 --- problems/0104.二叉树的最大深度.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 36578fd3..96169b32 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -38,7 +38,7 @@ 本题可以使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。 * 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始) -* 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始) +* 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始) **而根节点的高度就是二叉树的最大深度**,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。 From 9617a8b3fedc3996645977df31104159864b3462 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Mon, 1 May 2023 15:46:15 -0500 Subject: [PATCH 083/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 75 ++++++++++++++++++------------- 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 26f0ae2d..e777c2a4 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -171,47 +171,60 @@ python3代码: ```python +# 利用长度法 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +from collections import deque class Solution: - """二叉树层序遍历迭代解法""" - - def levelOrder(self, root: TreeNode) -> List[List[int]]: - results = [] + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: - return results - - from collections import deque - que = deque([root]) - - while que: - size = len(que) - result = [] - for _ in range(size): - cur = que.popleft() - result.append(cur.val) + return [] + queue = deque([root]) + result = [] + while queue: + level = [] + for _ in range(len(queue)): + cur = queue.popleft() + level.append(cur.val) if cur.left: - que.append(cur.left) + queue.append(cur.left) if cur.right: - que.append(cur.right) - results.append(result) - - return results + queue.append(cur.right) + result.append(level) + return result ``` - ```python # 递归法 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: - def levelOrder(self, root: TreeNode) -> List[List[int]]: - res = [] - def helper(root, depth): - if not root: return [] - if len(res) == depth: res.append([]) # start the current depth - res[depth].append(root.val) # fulfil the current depth - if root.left: helper(root.left, depth + 1) # process child nodes for the next depth - if root.right: helper(root.right, depth + 1) - helper(root, 0) - return res + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + levels = [] + self.helper(root, 0, levels) + return levels + + def helper(self, node, level, levels): + if not node: + return + if len(levels) == level: + levels.append([]) + levels[level].append(node.val) + self.helper(node.left, level + 1, levels) + self.helper(node.right, level + 1, levels) + + ``` + + go: ```go From 424d5c224f229aaee353b3bbae8996b8e5dcbef2 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 15:06:11 -0500 Subject: [PATCH 084/116] =?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 --- problems/0027.移除元素.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 91150c74..6dc6404e 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -198,6 +198,7 @@ Python: ``` python 3 +(版本一)快慢指针法 class Solution: def removeElement(self, nums: List[int], val: int) -> int: # 快慢指针 @@ -213,7 +214,21 @@ class Solution: return slow ``` - +``` python 3 +(版本二)暴力递归法 +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + i, l = 0, len(nums) + while i < l: + if nums[i] == val: # 找到等于目标值的节点 + for j in range(i+1, l): # 移除该元素,并将后面元素向前平移 + nums[j - 1] = nums[j] + l -= 1 + i -= 1 + i += 1 + return l + +``` Go: From 53fbfc8339a6b61cb708ec87356e764db0f2b1ba Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 15:08:17 -0500 Subject: [PATCH 085/116] =?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 --- problems/0027.移除元素.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 6dc6404e..90801153 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -215,7 +215,7 @@ class Solution: ``` ``` python 3 -(版本二)暴力递归法 +(版本二)暴力法 class Solution: def removeElement(self, nums: List[int], val: int) -> int: i, l = 0, len(nums) From 934dd4e3131485802edd5d7c45fd60dd4f8f2827 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 15:19:23 -0500 Subject: [PATCH 086/116] =?UTF-8?q?Update=200977.=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 41 ++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 57f8de02..4fbdd1cd 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -140,22 +140,37 @@ class Solution { Python: ```Python +(版本一)双指针法 class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: - n = len(nums) - i,j,k = 0,n - 1,n - 1 - ans = [-1] * n - while i <= j: - lm = nums[i] ** 2 - rm = nums[j] ** 2 - if lm > rm: - ans[k] = lm - i += 1 + l, r, i = 0, len(nums)-1, len(nums)-1 + res = [float('inf')] * len(nums) # 需要提前定义列表,存放结果 + while l <= r: + if nums[l] ** 2 < nums[r] ** 2: # 左右边界进行对比,找出最大值 + res[i] = nums[r] ** 2 + r -= 1 # 右指针往左移动 else: - ans[k] = rm - j -= 1 - k -= 1 - return ans + res[i] = nums[l] ** 2 + l += 1 # 左指针往右移动 + i -= 1 # 存放结果的指针需要往前平移一位 + return res +``` + +```Python +(版本二)暴力排序法 +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + for i in range(len(nums)): + nums[i] *= nums[i] + nums.sort() + return nums +``` + +```Python +(版本三)暴力排序法+列表推导法 +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + return sorted(x*x for x in nums) ``` Go: From 5f65e3ba24617dc81b199bcbb356f47517f7fbee Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 15:32:36 -0500 Subject: [PATCH 087/116] =?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 --- problems/0209.长度最小的子数组.md | 46 ++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 5a8f91af..d7ae4780 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -173,18 +173,44 @@ class Solution { Python: ```python +(版本一)滑动窗口法 class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: - res = float("inf") # 定义一个无限大的数 - Sum = 0 # 滑动窗口数值之和 - i = 0 # 滑动窗口起始位置 - for j in range(len(nums)): - Sum += nums[j] - while Sum >= s: - res = min(res, j-i+1) - Sum -= nums[i] - i += 1 - return 0 if res == float("inf") else res + l = len(nums) + left = 0 + right = 0 + min_len = float('inf') + cur_sum = 0 #当前的累加值 + + while right < l: + cur_sum += nums[right] + + while cur_sum >= s: # 当前累加值大于目标值 + min_len = min(min_len, right - left + 1) + cur_sum -= nums[left] + left += 1 + + right += 1 + + return min_len if min_len != float('inf') else 0 +``` + +```python +(版本二)暴力法 +class Solution: + def minSubArrayLen(self, s: int, nums: List[int]) -> int: + l = len(nums) + min_len = float('inf') + + for i in range(l): + cur_sum = 0 + for j in range(i, l): + cur_sum += nums[j] + if cur_sum >= s: + min_len = min(min_len, j - i + 1) + break + + return min_len if min_len != float('inf') else 0 ``` Go: From f45b1f1d28a668e2c90ad66ac0d2141d59fc73ae Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 16:19:13 -0500 Subject: [PATCH 088/116] =?UTF-8?q?Update=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index b52f16ea..6a0de282 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -307,21 +307,27 @@ public ListNode removeElements(ListNode head, int val) { Python: ```python +(版本一)虚拟头节点法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: - def removeElements(self, head: ListNode, val: int) -> ListNode: - dummy_head = ListNode(next=head) #添加一个虚拟节点 - cur = dummy_head - while cur.next: - if cur.next.val == val: - cur.next = cur.next.next #删除cur.next节点 + def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: + # 创建虚拟头部节点以简化删除过程 + dummy_head = ListNode(next = head) + + # 遍历列表并删除值为val的节点 + current = dummy_head + while current.next: + if current.next.val == val: + current.next = current.next.next else: - cur = cur.next + current = current.next + return dummy_head.next + ``` Go: From 70d8379ff7fe99edbbd2d006b9b3d9a5068c66fc Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 16:26:16 -0500 Subject: [PATCH 089/116] =?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 | 294 +++++++++++++++++++------------------- 1 file changed, 144 insertions(+), 150 deletions(-) diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index c72b7327..aa04d0e1 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -485,172 +485,166 @@ class MyLinkedList { Python: ```python -# 单链表 -class MyLinkedList1: - - def __init__(self): - self.dummy_head = Node()# 添加虚拟头指针,便于操作 - self.size = 0 # 设置一个链表长度的属性,便于后续操作,注意每次增和删的时候都要更新 - - def get(self, index): - """ - :type index: int - :rtype: int - """ - if index < 0 or index >= self.size: - return -1 - cur = self.dummy_head.next - while(index): - cur = cur.next - index -= 1 - return cur.val - - def addAtHead(self, val): - """ - :type val: int - :rtype: None - """ - new_node = Node(val) - new_node.next = self.dummy_head.next - self.dummy_head.next = new_node - self.size += 1 - - def addAtTail(self, val): - """ - :type val: int - :rtype: None - """ - new_node = Node(val) - cur = self.dummy_head - while(cur.next): - cur = cur.next - cur.next = new_node - self.size += 1 - - def addAtIndex(self, index, val): - """ - :type index: int - :type val: int - :rtype: None - """ - if index < 0: - self.addAtHead(val) - return - elif index == self.size: - self.addAtTail(val) - return - elif index > self.size: - return - - node = Node(val) - cur = self.dummy_head - while(index): - cur = cur.next - index -= 1 - node.next = cur.next - cur.next = node - self.size += 1 - - def deleteAtIndex(self, index): - """ - :type index: int - :rtype: None - """ - if index < 0 or index >= self.size: - return - pre = self.dummy_head - while(index): - pre = pre.next - index -= 1 - pre.next = pre.next.next - self.size -= 1 - -# 双链表 -# 相对于单链表, Node新增了prev属性 -class Node: - - def __init__(self, val=0, next = None, prev = None): +(版本一)单链表法 +class ListNode: + def __init__(self, val=0, next=None): self.val = val self.next = next - self.prev = prev - + class MyLinkedList: - def __init__(self): - self._head, self._tail = Node(0), Node(0) # 虚拟节点 - self._head.next, self._tail.prev = self._tail, self._head - self._count = 0 # 添加的节点数 - - def _get_node(self, index: int) -> Node: - # 当index小于_count//2时, 使用_head查找更快, 反之_tail更快 - if index >= self._count // 2: - # 使用prev往前找 - node = self._tail - for _ in range(self._count - index): - node = node.prev - else: - # 使用next往后找 - node = self._head - for _ in range(index + 1): - node = node.next - return node - - - def _update(self, prev: Node, next: Node, val: int) -> None: - """ - 更新节点 - :param prev: 相对于更新的前一个节点 - :param next: 相对于更新的后一个节点 - :param val: 要添加的节点值 - """ - # 计数累加 - self._count += 1 - node = Node(val) - prev.next, next.prev = node, node - node.prev, node.next = prev, next + self.dummy_head = ListNode() + self.size = 0 def get(self, index: int) -> int: - """ - Get the value of the index-th node in the linked list. If the index is invalid, return -1. - """ - if 0 <= index < self._count: - node = self._get_node(index) - return node.val - else: + if index < 0 or index >= self.size: return -1 + + current = self.dummy_head.next + for i in range(index): + current = current.next + + return current.val def addAtHead(self, val: int) -> None: - """ - Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. - """ - self._update(self._head, self._head.next, val) + self.dummy_head.next = ListNode(val, self.dummy_head.next) + self.size += 1 def addAtTail(self, val: int) -> None: - """ - Append a node of value val to the last element of the linked list. - """ - self._update(self._tail.prev, self._tail, val) + current = self.dummy_head + while current.next: + current = current.next + current.next = ListNode(val) + self.size += 1 def addAtIndex(self, index: int, val: int) -> None: - """ - Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. - """ - if index < 0: - index = 0 - elif index > self._count: + if index < 0 or index > self.size: return - node = self._get_node(index) - self._update(node.prev, node, val) + + current = self.dummy_head + for i in range(index): + current = current.next + current.next = ListNode(val, current.next) + self.size += 1 def deleteAtIndex(self, index: int) -> None: - """ - Delete the index-th node in the linked list, if the index is valid. - """ - if 0 <= index < self._count: - node = self._get_node(index) - # 计数-1 - self._count -= 1 - node.prev.next, node.next.prev = node.next, node.prev + if index < 0 or index >= self.size: + return + + current = self.dummy_head + for i in range(index): + current = current.next + current.next = current.next.next + self.size -= 1 + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) +``` + + +```python +(版本二)双链表法 +class ListNode: + def __init__(self, val=0, prev=None, next=None): + self.val = val + self.prev = prev + self.next = next + +class MyLinkedList: + def __init__(self): + self.head = None + self.tail = None + self.size = 0 + + def get(self, index: int) -> int: + if index < 0 or index >= self.size: + return -1 + + if index < self.size // 2: + current = self.head + for i in range(index): + current = current.next + else: + current = self.tail + for i in range(self.size - index - 1): + current = current.prev + + return current.val + + def addAtHead(self, val: int) -> None: + new_node = ListNode(val, None, self.head) + if self.head: + self.head.prev = new_node + else: + self.tail = new_node + self.head = new_node + self.size += 1 + + def addAtTail(self, val: int) -> None: + new_node = ListNode(val, self.tail, None) + if self.tail: + self.tail.next = new_node + else: + self.head = new_node + self.tail = new_node + self.size += 1 + + def addAtIndex(self, index: int, val: int) -> None: + if index < 0 or index > self.size: + return + + if index == 0: + self.addAtHead(val) + elif index == self.size: + self.addAtTail(val) + else: + if index < self.size // 2: + current = self.head + for i in range(index - 1): + current = current.next + else: + current = self.tail + for i in range(self.size - index): + current = current.prev + new_node = ListNode(val, current, current.next) + current.next.prev = new_node + current.next = new_node + self.size += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.size: + return + + if index == 0: + self.head = self.head.next + if self.head: + self.head.prev = None + else: + self.tail = None + elif index == self.size - 1: + self.tail = self.tail.prev + if self.tail: + self.tail.next = None + else: + self.head = None + else: + if index < self.size // 2: + current = self.head + for i in range(index): + current = current.next + else: + current = self.tail + for i in range(self.size - index - 1): + current = current.prev + current.prev.next = current.next + current.next.prev = current.prev + self.size -= 1 From 55ea26c5bdac70997c6ad9833448cdf3c1a7e0d1 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:18:48 -0500 Subject: [PATCH 090/116] =?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 --- problems/0206.翻转链表.md | 40 +++++++++++---------------------------- 1 file changed, 11 insertions(+), 29 deletions(-) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index d558e783..0425e182 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -193,9 +193,9 @@ class Solution { } ``` -Python迭代法: +Python ```python -#双指针 +(版本一)双指针法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): @@ -205,7 +205,7 @@ class Solution: def reverseList(self, head: ListNode) -> ListNode: cur = head pre = None - while(cur!=None): + while cur: temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next cur.next = pre #反转 #更新pre、cur指针 @@ -217,6 +217,7 @@ class Solution: Python递归法: ```python +(版本二)递归法 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): @@ -224,36 +225,17 @@ Python递归法: # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: - - def reverse(pre,cur): - if not cur: - return pre - - tmp = cur.next - cur.next = pre - - return reverse(cur,tmp) - - return reverse(None,head) + return self.reverse(head, None) + def reverse(self, cur: ListNode, pre: ListNode) -> ListNode: + if cur == None: + return pre + temp = cur.next + cur.next = pre + return self.reverse(temp, cur) ``` -Python递归法从后向前: -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: - if not head or not head.next: return head - p = self.reverseList(head.next) - head.next.next = head - head.next = None - return p -``` Go: From d92104209fecd89626df38414d03c78371f251e5 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:20:34 -0500 Subject: [PATCH 091/116] =?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 --- problems/0024.两两交换链表中的节点.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 4dc051aa..2c171dde 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -186,21 +186,20 @@ Python: class Solution: def swapPairs(self, head: ListNode) -> ListNode: - res = ListNode(next=head) - pre = res + dummy_head = ListNode(next=head) + current = dummy_head - # 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了 - while pre.next and pre.next.next: - cur = pre.next - post = pre.next.next + # 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了 + while current.next and current.next.next: + temp = current.next # 防止节点修改 + temp1 = current.next.next.next - # pre,cur,post对应最左,中间的,最右边的节点 - cur.next = post.next - post.next = cur - pre.next = post + current.next = current.next.next + current.next.next = temp + temp.next = temp1 + current = current.next.next + return dummy_head.next - pre = pre.next.next - return res.next ``` Go: From 190477400ebf0842343588c4e9e15c5eab412eb4 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:22:46 -0500 Subject: [PATCH 092/116] =?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 --- problems/0019.删除链表的倒数第N个节点.md | 28 +++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index a11ff8ba..c6f5bfc7 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -127,21 +127,29 @@ Python: # def __init__(self, val=0, next=None): # self.val = val # self.next = next + class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: - head_dummy = ListNode() - head_dummy.next = head - - slow, fast = head_dummy, head_dummy - while(n>=0): #fast先往前走n+1步 + # 创建一个虚拟节点,并将其下一个指针设置为链表的头部 + dummy_head = ListNode(0, head) + + # 创建两个指针,慢指针和快指针,并将它们初始化为虚拟节点 + slow = fast = dummy_head + + # 快指针比慢指针快 n+1 步 + for i in range(n+1): fast = fast.next - n -= 1 - while(fast!=None): + + # 移动两个指针,直到快速指针到达链表的末尾 + while fast: slow = slow.next fast = fast.next - #fast 走到结尾后,slow的下一个节点为倒数第N个节点 - slow.next = slow.next.next #删除 - return head_dummy.next + + # 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点 + slow.next = slow.next.next + + return dummy_head.next + ``` Go: ```Go From e4072d9a00b12c6de6949091378bdd8d95b5296c Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:25:36 -0500 Subject: [PATCH 093/116] =?UTF-8?q?Update=20=E9=9D=A2=E8=AF=95=E9=A2=9802.?= =?UTF-8?q?07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 63 +++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 30f5c467..4bcbd1f9 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -152,7 +152,7 @@ public class Solution { ### Python ```python - +(版本一)求长度,同时出发 class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lenA, lenB = 0, 0 @@ -178,7 +178,68 @@ class Solution: curB = curB.next return None ``` +```python +(版本二)求长度,同时出发 (代码复用) +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + lenA = self.getLength(headA) + lenB = self.getLength(headB) + + # 通过移动较长的链表,使两链表长度相等 + if lenA > lenB: + headA = self.moveForward(headA, lenA - lenB) + else: + headB = self.moveForward(headB, lenB - lenA) + + # 将两个头向前移动,直到它们相交 + while headA and headB: + if headA == headB: + return headA + headA = headA.next + headB = headB.next + + return None + + def getLength(self, head: ListNode) -> int: + length = 0 + while head: + length += 1 + head = head.next + return length + + def moveForward(self, head: ListNode, steps: int) -> ListNode: + while steps > 0: + head = head.next + steps -= 1 + return head +``` +```python +(版本三)等比例法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + # 处理边缘情况 + if not headA or not headB: + return None + + # 在每个链表的头部初始化两个指针 + pointerA = headA + pointerB = headB + + # 遍历两个链表直到指针相交 + while pointerA != pointerB: + # 将指针向前移动一个节点 + pointerA = pointerA.next if pointerA else headB + pointerB = pointerB.next if pointerB else headA + + # 如果相交,指针将位于交点节点,如果没有交点,值为None + return pointerA +``` ### Go ```go From b2bfb8016642f388389250df57bad7e9cce82a3f Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 17:27:27 -0500 Subject: [PATCH 094/116] =?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 --- problems/0142.环形链表II.md | 50 +++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 46df4777..e80a715a 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -221,25 +221,55 @@ public class Solution { Python: ```python +(版本一)快慢指针法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + class Solution: def detectCycle(self, head: ListNode) -> ListNode: - slow, fast = head, head + slow = head + fast = head + while fast and fast.next: slow = slow.next fast = fast.next.next - # 如果相遇 + + # If there is a cycle, the slow and fast pointers will eventually meet if slow == fast: - p = head - q = slow - while p!=q: - p = p.next - q = q.next - #你也可以return q - return p - + # Move one of the pointers back to the start of the list + slow = head + while slow != fast: + slow = slow.next + fast = fast.next + return slow + # If there is no cycle, return None return None ``` +```python +(版本二)集合法 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def detectCycle(self, head: ListNode) -> ListNode: + visited = set() + + while head: + if head in visited: + return head + visited.add(head) + head = head.next + + return None +``` Go: ```go From dd58553088514af1a1a019fb9e6d4b2e41b0aeb5 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 19:26:39 -0500 Subject: [PATCH 095/116] =?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 | 53 ++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 5a9a670a..8d5a5985 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -174,50 +174,45 @@ class Solution { Python: ```python # 前序遍历-递归-LC144_二叉树的前序遍历 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: - # 保存结果 - result = [] - - def traversal(root: TreeNode): - if root == None: - return - result.append(root.val) # 前序 - traversal(root.left) # 左 - traversal(root.right) # 右 + if not root: + return [] + + left = self.preorderTraversal(root.left) + right = self.preorderTraversal(root.right) + + return [root.val] + left + right - traversal(root) - return result # 中序遍历-递归-LC94_二叉树的中序遍历 class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: - result = [] + if root is None: + return [] - def traversal(root: TreeNode): - if root == None: - return - traversal(root.left) # 左 - result.append(root.val) # 中序 - traversal(root.right) # 右 + left = self.inorderTraversal(root.left) + right = self.inorderTraversal(root.right) - traversal(root) - return result + return left + [root.val] + right # 后序遍历-递归-LC145_二叉树的后序遍历 class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: - result = [] + if not root: + return [] - def traversal(root: TreeNode): - if root == None: - return - traversal(root.left) # 左 - traversal(root.right) # 右 - result.append(root.val) # 后序 + left = self.postorderTraversal(root.left) + right = self.postorderTraversal(root.right) - traversal(root) - return result + return left + right + [root.val] ``` Go: From dd1da7fc548c7ab7c1e0964f0ef50410be53e551 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 19:27:58 -0500 Subject: [PATCH 096/116] =?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 | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 8d5a5985..92f342f0 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -191,7 +191,8 @@ class Solution: return [root.val] + left + right - +``` +```python # 中序遍历-递归-LC94_二叉树的中序遍历 class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: @@ -202,6 +203,9 @@ class Solution: right = self.inorderTraversal(root.right) return left + [root.val] + right +``` +```python + # 后序遍历-递归-LC145_二叉树的后序遍历 class Solution: From ce5b335b7258b7febb2dc831d68bfd3bb6161905 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 19:30:53 -0500 Subject: [PATCH 097/116] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的迭代遍历.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 35cf4077..8b241465 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -258,7 +258,9 @@ class Solution: if node.left: stack.append(node.left) return result - +``` +```python + # 中序遍历-迭代-LC94_二叉树的中序遍历 class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: @@ -279,7 +281,9 @@ class Solution: # 取栈顶元素右结点 cur = cur.right return result - + ``` + ```python + # 后序遍历-迭代-LC145_二叉树的后序遍历 class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: From 0521f762d90b1af39fa4f134d219e2d208988e3b Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 19:48:57 -0500 Subject: [PATCH 098/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index e777c2a4..29deee11 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -178,12 +178,11 @@ python3代码: # self.val = val # self.left = left # self.right = right -from collections import deque class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return [] - queue = deque([root]) + queue = collections.deque([root]) result = [] while queue: level = [] From 42f85c8a8f8c637dbb484ca0d0c9ab88973c3a0b Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 19:56:26 -0500 Subject: [PATCH 099/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 36 ++++++++++++++++--------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 29deee11..a4164b2c 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -512,27 +512,29 @@ python代码: class Solution: """二叉树层序遍历II迭代解法""" +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: - results = [] if not root: - return results - - from collections import deque - que = deque([root]) - - while que: - result = [] - for _ in range(len(que)): - cur = que.popleft() - result.append(cur.val) + return [] + queue = collections.deque([root]) + result = [] + while queue: + level = [] + for _ in range(len(queue)): + cur = queue.popleft() + level.append(cur.val) if cur.left: - que.append(cur.left) + queue.append(cur.left) if cur.right: - que.append(cur.right) - results.append(result) - - results.reverse() - return results + queue.append(cur.right) + result.append(level) + return result[::-1] ``` Java: From 52092d0153828a14179b41d041e99121a9b4f1f2 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:01:07 -0500 Subject: [PATCH 100/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 46 +++++++++++++++---------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index a4164b2c..fdfde822 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -835,35 +835,35 @@ public: python代码: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] - - # deque来自collections模块,不在力扣平台时,需要手动写入 - # 'from collections import deque' 导入 - # deque相比list的好处是,list的pop(0)是O(n)复杂度,deque的popleft()是O(1)复杂度 - - quene = deque([root]) - out_list = [] - - while quene: - # 每次都取最后一个node就可以了 - node = quene[-1] - out_list.append(node.val) - - # 执行这个遍历的目的是获取下一层所有的node - for _ in range(len(quene)): - node = quene.popleft() + + queue = collections.deque([root]) + right_view = [] + + while queue: + level_size = len(queue) + + for i in range(level_size): + node = queue.popleft() + + if i == level_size - 1: + right_view.append(node.val) + if node.left: - quene.append(node.left) + queue.append(node.left) if node.right: - quene.append(node.right) - - return out_list - -# 执行用时:36 ms, 在所有 Python3 提交中击败了89.47%的用户 -# 内存消耗:14.6 MB, 在所有 Python3 提交中击败了96.65%的用户 + queue.append(node.right) + + return right_view ``` From 95616fa9a8a147f3255ead5523af0a4de51844b9 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:03:09 -0500 Subject: [PATCH 101/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 47 +++++++++++++++++++------------ 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index fdfde822..f4a5c466 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1121,27 +1121,38 @@ python代码: class Solution: """二叉树层平均值迭代解法""" +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: - results = [] if not root: - return results + return [] - from collections import deque - que = deque([root]) - - while que: - size = len(que) - sum_ = 0 - for _ in range(size): - cur = que.popleft() - sum_ += cur.val - if cur.left: - que.append(cur.left) - if cur.right: - que.append(cur.right) - results.append(sum_ / size) - - return results + queue = collections.deque([root]) + averages = [] + + while queue: + size = len(queue) + level_sum = 0 + + for i in range(size): + node = queue.popleft() + + + level_sum += node.val + + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + averages.append(level_sum / size) + + return averages ``` java: From 7be18e2dd372a17288c8cb215b52dc5a06c1a240 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:04:54 -0500 Subject: [PATCH 102/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 40 ++++++++++++++++++------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index f4a5c466..ed2c683d 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1426,28 +1426,36 @@ public: python代码: ```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + class Solution: - """N叉树的层序遍历迭代法""" - def levelOrder(self, root: 'Node') -> List[List[int]]: - results = [] if not root: - return results + return [] - from collections import deque - que = deque([root]) + result = [] + queue = collections.deque([root]) - while que: - result = [] - for _ in range(len(que)): - cur = que.popleft() - result.append(cur.val) - # cur.children 是 Node 对象组成的列表,也可能为 None - if cur.children: - que.extend(cur.children) - results.append(result) + while queue: + level_size = len(queue) + level = [] - return results + for _ in range(level_size): + node = queue.popleft() + level.append(node.val) + + for child in node.children: + queue.append(child) + + result.append(level) + + return result ``` ```python From 994db141aa831866a5551d7c01c5d676252b9876 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:06:39 -0500 Subject: [PATCH 103/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 39 +++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ed2c683d..6235ad21 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1761,22 +1761,37 @@ public: python代码: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: - if root is None: + if not root: return [] - queue = [root] - out_list = [] + + result = [] + queue = collections.deque([root]) + while queue: - length = len(queue) - in_list = [] - for _ in range(length): - curnode = queue.pop(0) - in_list.append(curnode.val) - if curnode.left: queue.append(curnode.left) - if curnode.right: queue.append(curnode.right) - out_list.append(max(in_list)) - return out_list + level_size = len(queue) + max_val = float('-inf') + + for _ in range(level_size): + node = queue.popleft() + max_val = max(max_val, node.val) + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) + + result.append(max_val) + + return result ``` java代码: From ffab57f2c330f35a624bd7c9ce7dc9d444f0ff79 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:09:12 -0500 Subject: [PATCH 104/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 48 +++++++++++++++++-------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 6235ad21..47969b25 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2096,36 +2096,40 @@ class Solution { python代码: ```python -# 层序遍历解法 +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" class Solution: def connect(self, root: 'Node') -> 'Node': if not root: - return None - queue = [root] + return root + + queue = collections.deque([root]) + while queue: - n = len(queue) - for i in range(n): - node = queue.pop(0) + level_size = len(queue) + prev = None + + for i in range(level_size): + node = queue.popleft() + + if prev: + prev.next = node + + prev = node + if node.left: queue.append(node.left) + if node.right: queue.append(node.right) - if i == n - 1: - break - node.next = queue[0] - return root - -# 链表解法 -class Solution: - def connect(self, root: 'Node') -> 'Node': - first = root - while first: - cur = first - while cur: # 遍历每一层的节点 - if cur.left: cur.left.next = cur.right # 找左节点的next - if cur.right and cur.next: cur.right.next = cur.next.left # 找右节点的next - cur = cur.next # cur同层移动到下一节点 - first = first.left # 从本层扩展到下一层 + return root ``` From 65085c4e9bcf8c478fe67caad7dd0dceaa5911e0 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:10:51 -0500 Subject: [PATCH 105/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 44 ++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 47969b25..89e7a126 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2381,21 +2381,41 @@ python代码: ```python # 层序遍历解法 +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + class Solution: def connect(self, root: 'Node') -> 'Node': if not root: - return None - queue = [root] - while queue: # 遍历每一层 - length = len(queue) - tail = None # 每一层维护一个尾节点 - for i in range(length): # 遍历当前层 - curnode = queue.pop(0) - if tail: - tail.next = curnode # 让尾节点指向当前节点 - tail = curnode # 让当前节点成为尾节点 - if curnode.left : queue.append(curnode.left) - if curnode.right: queue.append(curnode.right) + return root + + queue = collections.deque([root]) + + while queue: + level_size = len(queue) + prev = None + + for i in range(level_size): + node = queue.popleft() + + if prev: + prev.next = node + + prev = node + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) + return root ``` From 61173277185bf7948ffb576212cc31fd383778e3 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:12:16 -0500 Subject: [PATCH 106/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 89e7a126..13694207 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2664,24 +2664,31 @@ class Solution { Python: ```python 3 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: - if root == None: + if not root: return 0 - - queue_ = [root] + depth = 0 - while queue_: - length = len(queue_) - for i in range(length): - cur = queue_.pop(0) - sub.append(cur.val) - #子节点入队列 - if cur.left: queue_.append(cur.left) - if cur.right: queue_.append(cur.right) + queue = collections.deque([root]) + + while queue: depth += 1 - + for _ in range(len(queue)): + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + return depth + ``` Go: From de7c67c35a5d3d0e423072d0b7cb02876c628786 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:13:38 -0500 Subject: [PATCH 107/116] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 33 +++++++++++++++++-------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 13694207..c2ad9508 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2938,23 +2938,26 @@ Python 3: # self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: - if root == None: + if not root: return 0 + depth = 0 + queue = collections.deque([root]) + + while queue: + depth += 1 + for _ in range(len(queue)): + node = queue.popleft() + + if not node.left and not node.right: + return depth + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) - #根节点的深度为1 - queue_ = [(root,1)] - while queue_: - cur, depth = queue_.pop(0) - - if cur.left == None and cur.right == None: - return depth - #先左子节点,由于左子节点没有孩子,则就是这一层了 - if cur.left: - queue_.append((cur.left,depth + 1)) - if cur.right: - queue_.append((cur.right,depth + 1)) - - return 0 + return depth ``` Go: From 54bcab13e37ee1e609b567411b968bdb5a86abac Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:25:30 -0500 Subject: [PATCH 108/116] =?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 | 163 ++++++++++++++++++++++++++---------- 1 file changed, 120 insertions(+), 43 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 16a5be57..63baa409 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -314,81 +314,158 @@ class Solution { 递归法:前序遍历: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return None - root.left, root.right = root.right, root.left #中 - self.invertTree(root.left) #左 - self.invertTree(root.right) #右 + root.left, root.right = root.right, root.left + self.invertTree(root.left) + self.invertTree(root.right) return root ``` -递归法:后序遍历: +迭代法:前序遍历: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: - if root is None: + if not root: + return None + stack = [root] + while stack: + node = stack.pop() + node.left, node.right = node.right, node.left + if node.left: + stack.append(node.left) + if node.right: + stack.append(node.right) + return root +``` + + +递归法:中序遍历: +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: + return None + self.invertTree(root.left) + root.left, root.right = root.right, root.left + self.invertTree(root.left) + return root +``` + +迭代法:中序遍历: +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: + return None + stack = [root] + while stack: + node = stack.pop() + if node.left: + stack.append(node.left) + node.left, node.right = node.right, node.left + if node.left: + stack.append(node.left) + return root +``` + + +递归法:后序遍历: +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: return None self.invertTree(root.left) self.invertTree(root.right) root.left, root.right = root.right, root.left - return root + return root ``` -迭代法:深度优先遍历(前序遍历): +迭代法:后序遍历: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: - return root - st = [] - st.append(root) - while st: - node = st.pop() - node.left, node.right = node.right, node.left #中 - if node.right: - st.append(node.right) #右 + return None + stack = [root] + while stack: + node = stack.pop() if node.left: - st.append(node.left) #左 + stack.append(node.left) + if node.right: + stack.append(node.right) + node.left, node.right = node.right, node.left + return root ``` + + + + 迭代法:广度优先遍历(层序遍历): ```python -import collections +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: - queue = collections.deque() #使用deque() - if root: - queue.append(root) + if not root: + return None + + queue = collections.deque([root]) while queue: - size = len(queue) - for i in range(size): + for i in range(len(queue)): node = queue.popleft() - node.left, node.right = node.right, node.left #节点处理 - if node.left: - queue.append(node.left) - if node.right: - queue.append(node.right) - return root -``` -迭代法:广度优先遍历(层序遍历),和之前的层序遍历写法一致: -```python -class Solution: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - if not root: return root - from collections import deque - que=deque([root]) - while que: - size=len(que) - for i in range(size): - cur=que.popleft() - cur.left, cur.right = cur.right, cur.left - if cur.left: que.append(cur.left) - if cur.right: que.append(cur.right) + node.left, node.right = node.right, node.left + if node.left: queue.append(node.left) + if node.right: queue.append(node.right) return root + ``` + ### Go 递归版本的前序遍历 From 918d0ec0faf27870212b11c4820d4ae956ba8da3 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:40:43 -0500 Subject: [PATCH 109/116] =?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 --- problems/0101.对称二叉树.md | 40 +++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index b75e9ff2..81ca79a2 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -442,25 +442,31 @@ class Solution: 层次遍历 ```python class Solution: - def isSymmetric(self, root: Optional[TreeNode]) -> bool: + def isSymmetric(self, root: TreeNode) -> bool: if not root: return True - - que = [root] - while que: - this_level_length = len(que) - for i in range(this_level_length // 2): - # 要么其中一个是None但另外一个不是 - if (not que[i] and que[this_level_length - 1 - i]) or (que[i] and not que[this_level_length - 1 - i]): - return False - # 要么两个都不是None - if que[i] and que[i].val != que[this_level_length - 1 - i].val: - return False - for i in range(this_level_length): - if not que[i]: continue - que.append(que[i].left) - que.append(que[i].right) - que = que[this_level_length:] + + queue = collections.deque([root.left, root.right]) + + while queue: + level_size = len(queue) + + if level_size % 2 != 0: + return False + + level_vals = [] + for i in range(level_size): + node = queue.popleft() + if node: + level_vals.append(node.val) + queue.append(node.left) + queue.append(node.right) + else: + level_vals.append(None) + + if level_vals != level_vals[::-1]: + return False + return True ``` From aac7378cb62ed2ec36fc1012f0057844297bda67 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 21:40:49 -0500 Subject: [PATCH 110/116] =?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 --- problems/0104.二叉树的最大深度.md | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 36578fd3..2294c1d9 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -419,26 +419,33 @@ class solution: return 1 + max(self.maxdepth(root.left), self.maxdepth(root.right)) ``` -迭代法: +层序遍历迭代法: ```python -import collections -class solution: - def maxdepth(self, root: treenode) -> int: +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: if not root: return 0 - depth = 0 #记录深度 - queue = collections.deque() - queue.append(root) + + depth = 0 + queue = collections.deque([root]) + while queue: - size = len(queue) depth += 1 - for i in range(size): + for _ in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) + return depth + ``` ### 559.n叉树的最大深度 From 5da51519b5692ef2f450ba38b6299452a00f3b22 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 21:48:04 -0500 Subject: [PATCH 111/116] =?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 --- problems/0104.二叉树的最大深度.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 2294c1d9..c4d94d4d 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -452,14 +452,17 @@ class Solution: 递归法: ```python -class solution: - def maxdepth(self, root: 'node') -> int: +class Solution: + def maxDepth(self, root: 'Node') -> int: if not root: return 0 - depth = 0 - for i in range(len(root.children)): - depth = max(depth, self.maxdepth(root.children[i])) - return depth + 1 + + max_depth = 1 + + for child in root.children: + max_depth = max(max_depth, self.maxDepth(child) + 1) + + return max_depth ``` 迭代法: From be27cc547daf4c82a048b71f201c93ed3b2b3e2e Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 21:57:13 -0500 Subject: [PATCH 112/116] =?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 --- problems/0104.二叉树的最大深度.md | 33 ++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index c4d94d4d..c55ddb3f 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -467,22 +467,31 @@ class Solution: 迭代法: ```python -import collections -class solution: - def maxdepth(self, root: 'node') -> int: - queue = collections.deque() - if root: - queue.append(root) - depth = 0 #记录深度 +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: + return 0 + + depth = 0 + queue = collections.deque([root]) + while queue: - size = len(queue) depth += 1 - for i in range(size): + for _ in range(len(queue)): node = queue.popleft() - for j in range(len(node.children)): - if node.children[j]: - queue.append(node.children[j]) + for child in node.children: + queue.append(child) + return depth + ``` 使用栈来模拟后序遍历依然可以 From 1b1b51750db1afcb812ba1250ea4fdc3e0395425 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 22:04:25 -0500 Subject: [PATCH 113/116] =?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 --- problems/0104.二叉树的最大深度.md | 48 ++++++++++++++++--------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index c55ddb3f..b6208169 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -494,30 +494,32 @@ class Solution: ``` -使用栈来模拟后序遍历依然可以 +使用栈 ```python -class solution: - def maxdepth(self, root: 'node') -> int: - st = [] - if root: - st.append(root) - depth = 0 - result = 0 - while st: - node = st.pop() - if node != none: - st.append(node) #中 - st.append(none) - depth += 1 - for i in range(len(node.children)): #处理孩子 - if node.children[i]: - st.append(node.children[i]) - - else: - node = st.pop() - depth -= 1 - result = max(result, depth) - return result +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + +class Solution: + def maxDepth(self, root: 'Node') -> int: + if not root: + return 0 + + max_depth = 0 + + stack = [(root, 1)] + + while stack: + node, depth = stack.pop() + max_depth = max(max_depth, depth) + for child in node.children: + stack.append((child, depth + 1)) + + return max_depth ``` From 75d137eb1c0464de0321f611ed66125e322936e7 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 00:23:53 -0500 Subject: [PATCH 114/116] =?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 --- problems/0111.二叉树的最小深度.md | 59 ++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 20 deletions(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index de36c6f2..bda12ff0 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -300,44 +300,63 @@ class Solution { 递归法: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: if not root: return 0 + if not root.left and not root.right: return 1 - - min_depth = 10**9 + + left_depth = float('inf') + right_depth = float('inf') + if root.left: - min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度 + left_depth = self.minDepth(root.left) if root.right: - min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度 - return min_depth + 1 + right_depth = self.minDepth(root.right) + + return 1 + min(left_depth, right_depth) + ``` 迭代法: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def 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() - # 当左右孩子都为空的时候,说明是最低点的一层了,退出 + depth = 0 + queue = collections.deque([root]) + + while queue: + depth += 1 + for _ in range(len(queue)): + node = queue.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 + return depth + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) + + return depth ``` From d15c54f43fe0df608d207f269e8bb589c5cebd3d Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 00:26:20 -0500 Subject: [PATCH 115/116] =?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 --- problems/0111.二叉树的最小深度.md | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index bda12ff0..0c086f1b 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -359,6 +359,39 @@ class Solution: return depth ``` +迭代法: + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + + queue = collections.deque([(root, 1)]) + + while queue: + node, depth = queue.popleft() + + # Check if the node is a leaf node + if not node.left and not node.right: + return depth + + # Add left and right child to the queue + if node.left: + queue.append((node.left, depth+1)) + if node.right: + queue.append((node.right, depth+1)) + + return 0 + +``` ## Go From 3d59f732e0479c12657f5a6020b4ed5784222780 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Thu, 4 May 2023 01:35:13 -0500 Subject: [PATCH 116/116] =?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 --- problems/0222.完全二叉树的节点个数.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index d89a9bce..795a6f37 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -393,6 +393,20 @@ class Solution: # 利用完全二叉树特性 return 2**count-1 return 1+self.countNodes(root.left)+self.countNodes(root.right) ``` +完全二叉树写法3 +```python +class Solution: # 利用完全二叉树特性 + def countNodes(self, root: TreeNode) -> int: + if not root: return 0 + count = 0 + left = root.left; right = root.right + while left and right: + count+=1 + left = left.left; right = right.right + if not left and not right: # 如果同时到底说明是满二叉树,反之则不是 + return (2<