From ca89ca30975554cd3130eb6a2f6101c80723f99f Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 27 Nov 2023 10:16:15 +0800 Subject: [PATCH 01/59] =?UTF-8?q?Update=200700.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0700.二叉搜索树中的搜索.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index bc21bab8..65e69219 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -464,6 +464,28 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public TreeNode SearchBST(TreeNode root, int val) +{ + if (root == null || root.val == val) return root; + if (root.val > val) return SearchBST(root.left, val); + if (root.val < val) return SearchBST(root.right, val); + return null; +} +// 迭代 +public TreeNode SearchBST(TreeNode root, int val) +{ + while (root != null) + { + if (root.val > val) root = root.left; + else if (root.val < val) root = root.right; + else return root; + } + return null; +} +```

From 7aef42def84ef94f198eedd85a946130319264da Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 28 Nov 2023 10:17:25 +0800 Subject: [PATCH 02/59] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?C#=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 184060a5..319ad1aa 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -791,6 +791,20 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public long val = Int64.MinValue; +public bool IsValidBST(TreeNode root) +{ + if (root == null) return true; + bool left = IsValidBST(root.left); + if (root.val > val) val = root.val; + else return false; + bool right = IsValidBST(root.right); + return left && right; +} +```

From bc7f72cad70d1459f290a85f02447c43939606d3 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 29 Nov 2023 09:05:34 +0800 Subject: [PATCH 03/59] =?UTF-8?q?Update=20530.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E7=BB=9D=E5=AF=B9?= =?UTF-8?q?=E5=B7=AE=EF=BC=8C=E6=B7=BB=E5=8A=A0C#=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0530.二叉搜索树的最小绝对差.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 56911858..f08df577 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -647,6 +647,27 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public class Solution +{ + public List res = new List(); + public int GetMinimumDifference(TreeNode root) + { + Traversal(root); + return res.SelectMany((x, i) => res.Skip(i + 1).Select(y => Math.Abs(x - y))).Min(); + + } + public void Traversal(TreeNode root) + { + if (root == null) return; + Traversal(root.left); + res.Add(root.val); + Traversal(root.right); + } +} +```

From 26df976d6297777e5f984746f72ad9f453e13e0b Mon Sep 17 00:00:00 2001 From: QZ-z <55394467+QZ-z@users.noreply.github.com> Date: Wed, 29 Nov 2023 13:17:40 +0800 Subject: [PATCH 04/59] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改java程序快指针代码,删除循环条件中的= --- problems/0019.删除链表的倒数第N个节点.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 28bb61ee..f508b523 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -106,7 +106,7 @@ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode slowIndex = dummyNode; // 只要快慢指针相差 n 个结点即可 - for (int i = 0; i <= n ; i++){ + for (int i = 0; i < n ; i++){ fastIndex = fastIndex.next; } From 22ae299a273f69ebbc7411309b9dfee3c2e2a9d3 Mon Sep 17 00:00:00 2001 From: Echo0701 <133868458+Echo0701@users.noreply.github.com> Date: Thu, 30 Nov 2023 18:48:52 +0800 Subject: [PATCH 05/59] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=A4=9A?= =?UTF-8?q?=E9=87=8D=E8=83=8C=E5=8C=85=E7=9A=84=20Java=20=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 --- .../背包问题理论基础多重背包.md | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md index b19b5273..5d6440e3 100644 --- a/problems/背包问题理论基础多重背包.md +++ b/problems/背包问题理论基础多重背包.md @@ -165,7 +165,43 @@ int main() { ### Java: +```Java +import java.util.Scanner; +class multi_pack{ + public static void main(String [] args) { + Scanner sc = new Scanner(System.in); + /** + * bagWeight:背包容量 + * n:物品种类 + */ + int bagWeight, n; + + //获取用户输入数据,中间用空格隔开,回车键换行 + bagWeight = sc.nextInt(); + n = sc.nextInt(); + int[] weight = new int[n]; + int[] value = new int[n]; + int[] nums = new int[n]; + for (int i = 0; i < n; i++) weight[i] = sc.nextInt(); + for (int i = 0; i < n; i++) value[i] = sc.nextInt(); + for (int i = 0; i < n; i++) nums[i] = sc.nextInt(); + + int[] dp = new int[bagWeight + 1]; + + //先遍历物品再遍历背包,作为01背包处理 + for (int i = 0; i < n; i++) { + for (int j = bagWeight; j >= weight[i]; j--) { + //遍历每种物品的个数 + for (int k = 1; k <= nums[i] && (j - k * weight[i]) >= 0; k++) { + dp[j] = Math.max(dp[j], dp[j - k * weight[i]] + k * value[i]); + } + } + } + System.out.println(dp[bagWeight]); + } +} +``` ### Python: ### Go: From 0ed113487080dd4cf99d3048863f67c267af96aa Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 3 Dec 2023 09:41:53 +0800 Subject: [PATCH 06/59] =?UTF-8?q?Update=200501.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 8881200f..5b26d580 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -1009,6 +1009,46 @@ pub fn find_mode(root: Option>>) -> Vec { res } ``` +### C# +```C# +// 递归 +public class Solution +{ + public List res = new List(); + public int count = 0; + public int maxCount = 0; + public TreeNode pre = null; + public int[] FindMode(TreeNode root) + { + SearchBST(root); + return res.ToArray(); + } + public void SearchBST(TreeNode root) + { + if (root == null) return; + SearchBST(root.left); + if (pre == null) + count = 1; + else if (pre.val == root.val) + count++; + else + count = 1; + + pre = root; + if (count == maxCount) + { + res.Add(root.val); + } + else if (count > maxCount) + { + res.Clear(); + res.Add(root.val); + maxCount = count; + } + SearchBST(root.right); + } +} +```

From a0e2c5ceb06d9199bc6f2ce2eb0aa87a8ebf8fe4 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 4 Dec 2023 09:42:53 +0800 Subject: [PATCH 07/59] =?UTF-8?q?Update0236.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= =?UTF-8?q?=EF=BC=8C=E6=8F=90=E4=BA=A4C#=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0236.二叉树的最近公共祖先.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index edb5ea3e..0e99f1c2 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -431,6 +431,19 @@ impl Solution { } } ``` +### C# +```C# +public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) +{ + if (root == null || root == p || root == q) return root; + TreeNode left = LowestCommonAncestor(root.left, p, q); + TreeNode right = LowestCommonAncestor(root.right, p, q); + if (left != null && right != null) return root; + if (left == null && right != null) return right; + if (left != null && right == null) return left; + return null; +} +```

From 09e230bef32642e1e00f6223b83749a93989d70c Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 5 Dec 2023 09:08:03 +0800 Subject: [PATCH 08/59] =?UTF-8?q?Update0235.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=A5=96=E5=85=88=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b7e92e4e..b27a231e 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -513,6 +513,31 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) +{ + if (root.val > p.val && root.val > q.val) + return LowestCommonAncestor(root.left, p, q); + if (root.val < p.val && root.val < q.val) + return LowestCommonAncestor(root.right, p, q); + return root; +} +// 迭代 +public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) +{ + while (root != null) + { + if (root.val > p.val && root.val > q.val) + root = root.left; + else if (root.val < p.val && root.val < q.val) + root = root.right; + else return root; + } + return null; +} +```

From 29b7e23ac9d3c063e4e2c2e3ccf90cdf49eacf10 Mon Sep 17 00:00:00 2001 From: block <1181882120@qq.com> Date: Tue, 5 Dec 2023 09:57:09 +0800 Subject: [PATCH 09/59] Update minimum deepth doc --- problems/0111.二叉树的最小深度.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index b27df4a6..46523349 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -50,7 +50,7 @@ ![111.二叉树的最小深度](https://code-thinking.cdn.bcebos.com/pics/111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.png) -这就重新审题了,题目中说的是:**最小深度是从根节点到最近叶子节点的最短路径上的节点数量。**,注意是**叶子节点**。 +这就重新审题了,题目中说的是:**最小深度是从根节点到最近叶子节点的最短路径上的节点数量。**注意是**叶子节点**。 什么是叶子节点,左右孩子都为空的节点才是叶子节点! From a18bca36254163df96b811b8598f2d07081369ec Mon Sep 17 00:00:00 2001 From: LePing Huang <94521862+hlp777@users.noreply.github.com> Date: Tue, 5 Dec 2023 16:52:40 +0800 Subject: [PATCH 10/59] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF=E4=B8=8A?= =?UTF-8?q?=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 最新力扣新增测试案例 nums = [0] 预期输出 1 实际输出 0 就是nums.length == 0 时 要return 1 --- problems/0300.最长上升子序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 677c72c6..64f75291 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -130,7 +130,7 @@ public: class Solution { public int lengthOfLIS(int[] nums) { int[] dp = new int[nums.length]; - int res = 0; + int res = 1; Arrays.fill(dp, 1); for (int i = 1; i < dp.length; i++) { for (int j = 0; j < i; j++) { From 35322cb120cd2d64e1e760eb6662fa68dded9e2b Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 6 Dec 2023 09:05:08 +0800 Subject: [PATCH 11/59] =?UTF-8?q?Update0701.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0701.二叉搜索树中的插入操作.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 265bbb5b..98e60d5f 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -691,6 +691,17 @@ impl Solution { } } ``` +### C# +``` C# +// 递归 +public TreeNode InsertIntoBST(TreeNode root, int val) { + if (root == null) return new TreeNode(val); + + if (root.val > val) root.left = InsertIntoBST(root.left, val); + if (root.val < val) root.right = InsertIntoBST(root.right, val); + return root; +} +```

From be7fd6753a8b2a00ce24f1766c67e13f1d6ef69f Mon Sep 17 00:00:00 2001 From: freshield Date: Fri, 8 Dec 2023 06:56:25 +0800 Subject: [PATCH 12/59] =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=AB=A0=E8=8A=82=20->=20?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E6=95=B0=E5=AD=97=E7=9A=84GO=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E5=8F=8C=E6=8C=87=E9=92=88=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama54.替换数字.md | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/kama54.替换数字.md b/problems/kama54.替换数字.md index d5abbc4d..a7e0c7f0 100644 --- a/problems/kama54.替换数字.md +++ b/problems/kama54.替换数字.md @@ -183,6 +183,54 @@ func main(){ fmt.Printf(string(strByte)) } ```` +Go使用双指针解法 +````go +package main + +import "fmt" + +func replaceNumber(strByte []byte) string { + // 查看有多少字符 + numCount, oldSize := 0, len(strByte) + for i := 0; i < len(strByte); i++ { + if (strByte[i] <= '9') && (strByte[i] >= '0') { + numCount ++ + } + } + // 增加长度 + for i := 0; i < numCount; i++ { + strByte = append(strByte, []byte(" ")...) + } + tmpBytes := []byte("number") + // 双指针从后遍历 + leftP, rightP := oldSize-1, len(strByte)-1 + for leftP < rightP { + rightShift := 1 + // 如果是数字则加入number + if (strByte[leftP] <= '9') && (strByte[leftP] >= '0') { + for i, tmpByte := range tmpBytes { + strByte[rightP-len(tmpBytes)+i+1] = tmpByte + } + rightShift = len(tmpBytes) + } else { + strByte[rightP] = strByte[leftP] + } + // 更新指针 + rightP -= rightShift + leftP -= 1 + } + return string(strByte) +} + +func main(){ + var strByte []byte + fmt.Scanln(&strByte) + + newString := replaceNumber(strByte) + + fmt.Println(newString) +} +```` From 7692d6cc97a999016aa0bd023433a2e0975e262d Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 8 Dec 2023 08:08:10 +0800 Subject: [PATCH 13/59] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0669.修剪二叉搜索树.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 00186558..229a2ab1 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -567,6 +567,23 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public TreeNode TrimBST(TreeNode root, int low, int high) +{ + if (root == null) return null; + if (root.val < low) + return TrimBST(root.right, low, high); + + if (root.val > high) + return TrimBST(root.left, low, high); + + root.left = TrimBST(root.left, low, high); + root.right = TrimBST(root.right, low, high); + return root; +} +```

From 3427281196aadee968f41e92ca9beca7aaf81211 Mon Sep 17 00:00:00 2001 From: freshield Date: Fri, 8 Dec 2023 12:36:49 +0800 Subject: [PATCH 14/59] =?UTF-8?q?Fix:=20=E4=BF=AE=E6=AD=A3markdown?= =?UTF-8?q?=E4=B8=AD=E7=9A=84tab=E4=B8=BA=E7=A9=BA=E6=A0=BC=EF=BC=8C?= =?UTF-8?q?=E6=8E=92=E9=99=A4=E6=98=BE=E7=A4=BA=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama54.替换数字.md | 68 ++++++++++++++++----------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/problems/kama54.替换数字.md b/problems/kama54.替换数字.md index a7e0c7f0..0f8daa21 100644 --- a/problems/kama54.替换数字.md +++ b/problems/kama54.替换数字.md @@ -190,45 +190,45 @@ package main import "fmt" func replaceNumber(strByte []byte) string { - // 查看有多少字符 - numCount, oldSize := 0, len(strByte) - for i := 0; i < len(strByte); i++ { - if (strByte[i] <= '9') && (strByte[i] >= '0') { - numCount ++ - } - } - // 增加长度 - for i := 0; i < numCount; i++ { - strByte = append(strByte, []byte(" ")...) - } - tmpBytes := []byte("number") - // 双指针从后遍历 - leftP, rightP := oldSize-1, len(strByte)-1 - for leftP < rightP { - rightShift := 1 - // 如果是数字则加入number - if (strByte[leftP] <= '9') && (strByte[leftP] >= '0') { - for i, tmpByte := range tmpBytes { - strByte[rightP-len(tmpBytes)+i+1] = tmpByte - } - rightShift = len(tmpBytes) - } else { - strByte[rightP] = strByte[leftP] - } - // 更新指针 - rightP -= rightShift - leftP -= 1 - } - return string(strByte) + // 查看有多少字符 + numCount, oldSize := 0, len(strByte) + for i := 0; i < len(strByte); i++ { + if (strByte[i] <= '9') && (strByte[i] >= '0') { + numCount ++ + } + } + // 增加长度 + for i := 0; i < numCount; i++ { + strByte = append(strByte, []byte(" ")...) + } + tmpBytes := []byte("number") + // 双指针从后遍历 + leftP, rightP := oldSize-1, len(strByte)-1 + for leftP < rightP { + rightShift := 1 + // 如果是数字则加入number + if (strByte[leftP] <= '9') && (strByte[leftP] >= '0') { + for i, tmpByte := range tmpBytes { + strByte[rightP-len(tmpBytes)+i+1] = tmpByte + } + rightShift = len(tmpBytes) + } else { + strByte[rightP] = strByte[leftP] + } + // 更新指针 + rightP -= rightShift + leftP -= 1 + } + return string(strByte) } func main(){ - var strByte []byte - fmt.Scanln(&strByte) - + var strByte []byte + fmt.Scanln(&strByte) + newString := replaceNumber(strByte) - fmt.Println(newString) + fmt.Println(newString) } ```` From 5c20612aba9755626fe75688d367ebe68714d22e Mon Sep 17 00:00:00 2001 From: eat to 160 pounds <2915390277@qq.com> Date: Fri, 8 Dec 2023 20:27:07 +0800 Subject: [PATCH 15/59] =?UTF-8?q?feat:0322=E9=87=8D=E6=96=B0=E5=AE=89?= =?UTF-8?q?=E6=8E=92=E8=A1=8C=E7=A8=8B=20=E6=B7=BB=E5=8A=A0JavaScript?= =?UTF-8?q?=E7=89=88=E6=9C=AC=20=E5=A4=84=E7=90=86=E5=AF=B9=E8=B1=A1key?= =?UTF-8?q?=E6=97=A0=E5=BA=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 70 +++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index d1fd46f6..1473ed05 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -562,6 +562,7 @@ func findItinerary(tickets [][]string) []string { ``` ### Javascript + ```Javascript var findItinerary = function(tickets) { @@ -605,6 +606,74 @@ var findItinerary = function(tickets) { ``` +**javascript版本二 处理对象key无序问题** + +```javascript +/** + * @param {string[][]} tickets + * @return {string[]} + */ +var findItinerary = function (tickets) { + const ans = ["JFK"]; + let map = {}; + // 整理每个站点的终点站信息 + tickets.forEach((t) => { + let targets = map[t[0]]; + if (!targets) { + targets = { [t[1]]: 0 }; + map[t[0]] = targets; + } + targets[t[1]] = (targets[t[1]] || 0) + 1; + }); + // 按照key字典序排序对象 + const sortObject = (obj) => { + const newObj = {}; + const keys = Object.keys(obj); + keys.sort((k1, k2) => (k1 < k2 ? -1 : 1)); + keys.forEach((key) => { + if (obj[key] !== null && typeof obj[key] === "object") { + newObj[key] = sortObject(obj[key]); + } else { + newObj[key] = obj[key]; + } + }); + return newObj; + }; + const backtrack = (tickets, targets) => { + if (ans.length === tickets.length + 1) { + return true; + } + const target = targets[ans[ans.length - 1]]; + // 没有下一站 + if (!target) { + return false; + } + // 或者在这里排序 + // const keyList = Object.keys(target).sort((k1, k2) => (k1 < k2 ? -1 : 1)); + const keyList = Object.keys(target); + for (const key of keyList) { + // 判断当前站是否还能飞 + if (target[key] > 0) { + target[key]--; + ans.push(key); + // 对象key有序 此时的行程就是字典序最小的 直接跳出 + if (backtrack(tickets, targets)) { + return true; + } + target[key]++; + ans.pop(); + } + } + return false; + }; + map = sortObject(map); + backtrack(tickets, map); + return ans; +}; +``` + + + ### TypeScript ```typescript @@ -901,3 +970,4 @@ impl Solution { + From c0c5e38d9ffe16161aceb6658ec515bd50ca57f3 Mon Sep 17 00:00:00 2001 From: eat to 160 pounds <2915390277@qq.com> Date: Fri, 8 Dec 2023 21:51:19 +0800 Subject: [PATCH 16/59] =?UTF-8?q?feat:=200051.N=E7=9A=87=E5=90=8E=20?= =?UTF-8?q?=E6=9B=B4=E7=AE=80=E6=B4=81=E6=B8=85=E6=99=B0=E7=9A=84javascrip?= =?UTF-8?q?t=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 114 ++++++++++++++++++++------------------- 1 file changed, 60 insertions(+), 54 deletions(-) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 6bc4fa78..f6290793 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -453,60 +453,66 @@ func isValid(n, row, col int, chessboard [][]string) bool { ### Javascript ```Javascript -var solveNQueens = function(n) { - function isValid(row, col, chessBoard, n) { - - for(let i = 0; i < row; i++) { - if(chessBoard[i][col] === 'Q') { - return false - } - } - - for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { - if(chessBoard[i][j] === 'Q') { - return false - } - } - - for(let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { - if(chessBoard[i][j] === 'Q') { - return false - } - } - return true - } - - function transformChessBoard(chessBoard) { - let chessBoardBack = [] - chessBoard.forEach(row => { - let rowStr = '' - row.forEach(value => { - rowStr += value - }) - chessBoardBack.push(rowStr) - }) - - return chessBoardBack - } - - let result = [] - function backtracing(row,chessBoard) { - if(row === n) { - result.push(transformChessBoard(chessBoard)) - return - } - for(let col = 0; col < n; col++) { - if(isValid(row, col, chessBoard, n)) { - chessBoard[row][col] = 'Q' - backtracing(row + 1,chessBoard) - chessBoard[row][col] = '.' - } - } - } - let chessBoard = new Array(n).fill([]).map(() => new Array(n).fill('.')) - backtracing(0,chessBoard) - return result - +/** + * @param {number} n + * @return {string[][]} + */ +var solveNQueens = function (n) { + const ans = []; + const path = []; + const matrix = new Array(n).fill(0).map(() => new Array(n).fill(".")); + // 判断是否能相互攻击 + const canAttack = (matrix, row, col) => { + let i; + let j; + // 判断正上方和正下方是否有皇后 + for (i = 0, j = col; i < n; i++) { + if (matrix[i][j] === "Q") { + return true; + } + } + // 判断正左边和正右边是否有皇后 + for (i = row, j = 0; j < n; j++) { + if (matrix[i][j] === "Q") { + return true; + } + } + // 判断左上方是否有皇后 + for (i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { + if (matrix[i][j] === "Q") { + return true; + } + } + // 判断右上方是否有皇后 + for (i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { + if (matrix[i][j] === "Q") { + return true; + } + } + return false; + }; + const backtrack = (matrix, row, col) => { + if (path.length === matrix.length) { + ans.push(path.slice()); + return; + } + for (let i = row; i < matrix.length; i++) { + for (let j = col; j < matrix.length; j++) { + // 当前位置会导致互相攻击 继续下一轮搜索 + if (canAttack(matrix, i, j)) { + continue; + } + matrix[i][j] = "Q"; + path.push(matrix[i].join("")); + // 另起一行搜索 同一行只能有一个皇后 + backtrack(matrix, i + 1, 0); + matrix[i][j] = "."; + path.pop(); + } + } + }; + backtrack(matrix, 0, 0); + return ans; }; ``` From 0e55c1b424c4dac5cb78c304f412fce9fec14e47 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 9 Dec 2023 09:35:59 +0800 Subject: [PATCH 17/59] =?UTF-8?q?Update0108.=E5=B0=86=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E8=BD=AC=E6=8D=A2=E4=B8=BA=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...8.将有序数组转换为二叉搜索树.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index e699005e..4ccfc5f1 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -530,6 +530,23 @@ impl Solution { } } ``` +### C# +```csharp +// 递归 +public TreeNode SortedArrayToBST(int[] nums) +{ + return Traversal(nums, 0, nums.Length - 1); +} +public TreeNode Traversal(int[] nums, int left, int right) +{ + if (left > right) return null; + int mid = left + (right - left) / 2; + TreeNode node = new TreeNode(nums[mid]); + node.left = Traversal(nums, left, mid - 1); + node.right = Traversal(nums, mid + 1, right); + return node; +} +```

From e59dbae465c5247ff044a7d7fecd0b1cb6e22efe Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 10 Dec 2023 09:25:18 +0800 Subject: [PATCH 18/59] =?UTF-8?q?update538.=E6=8A=8A=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC=E6=8D=A2=E4=B8=BA=E7=B4=AF?= =?UTF-8?q?=E5=8A=A0=E6=A0=91=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0538.把二叉搜索树转换为累加树.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index c403c98f..07cae1ad 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -529,6 +529,23 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public class Solution +{ + int pre = 0; + public TreeNode ConvertBST(TreeNode root) + { + if (root == null) return null; + ConvertBST(root.right); + root.val += pre; + pre = root.val; + ConvertBST(root.left); + return root; + } +} +```

From 8de2e21d59d9fe68a9ac237affecf07b780c103f Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 11 Dec 2023 09:35:55 +0800 Subject: [PATCH 19/59] =?UTF-8?q?Update0077.=E7=BB=84=E5=90=88=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 54 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index a7f00ffe..8bca6f24 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -792,7 +792,59 @@ def backtracking(result, path, n, j, k) end ``` - +### C# +```C# +// 暴力 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> Combine(int n, int k) + { + BackTracking(n, k, 1); + return res; + } + public void BackTracking(int n, int k, int start) + { + if (path.Count == k) + { + res.Add(new List(path)); + return; + } + for (int i = start; i <= n; i++) + { + path.Add(i); + BackTracking(n, k, i + 1); + path.RemoveAt(path.Count - 1); + } + } +} +// 剪枝 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> Combine(int n, int k) + { + BackTracking(n, k, 1); + return res; + } + public void BackTracking(int n, int k, int start) + { + if (path.Count == k) + { + res.Add(new List(path)); + return; + } + for (int i = start; i <= n - (k - path.Count) + 1; i++) + { + path.Add(i); + BackTracking(n, k, i + 1); + path.RemoveAt(path.Count - 1); + } + } +} +```

From d3e61f36abf8b40fa9afac4e7c414f13d8bfcec7 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 12 Dec 2023 09:20:04 +0800 Subject: [PATCH 20/59] =?UTF-8?q?Update0216.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8C3=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0216.组合总和III.md | 61 +++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index c0cb8860..ac28f9fc 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -633,7 +633,66 @@ object Solution { } } ``` - +### C# +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum3(int k, int n) + { + BackTracking(k, n, 0, 1); + return res; + } + public void BackTracking(int k, int n, int sum, int start) + { + if (path.Count == k) + { + if (sum == n) + res.Add(new List(path)); + return; + } + for (int i = start; i <= 9; i++) + { + sum += i; + path.Add(i); + BackTracking(k, n, sum, i + 1); + sum -= i; + path.RemoveAt(path.Count - 1); + } + } +} +// 剪枝 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum3(int k, int n) + { + BackTracking(k, n, 0, 1); + return res; + } + public void BackTracking(int k, int n, int sum, int start) + { + if (sum > n) + return; + if (path.Count == k) + { + if (sum == n) + res.Add(new List(path)); + return; + } + for (int i = start; i <= 9 - (k - path.Count) + 1; i++) + { + sum += i; + path.Add(i); + BackTracking(k, n, sum, i + 1); + sum -= i; + path.RemoveAt(path.Count - 1); + } + } +} +``` From c14df2f5779314078744090b62d9745f34de1d24 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 13 Dec 2023 09:45:51 +0800 Subject: [PATCH 21/59] =?UTF-8?q?Update0017.=E7=94=B5=E8=AF=9D=E5=8F=B7?= =?UTF-8?q?=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 90296efd..a77bce46 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -732,6 +732,38 @@ def backtracking(result, letter_map, digits, path, index) end end ``` +### C# +```C# +public class Solution +{ + public IList res = new List(); + public string s; + public string[] letterMap = new string[10] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; + public IList LetterCombinations(string digits) + { + if (digits.Length == 0) + return res; + BackTracking(digits, 0); + return res; + } + public void BackTracking(string digits, int index) + { + if (index == digits.Length) + { + res.Add(s); + return; + } + int digit = digits[index] - '0'; + string letters = letterMap[digit]; + for (int i = 0; i < letters.Length; i++) + { + s += letters[i]; + BackTracking(digits, index + 1); + s = s.Substring(0, s.Length - 1); + } + } +} +```

From 3b507ac7552655dc98ea198259103280e4601804 Mon Sep 17 00:00:00 2001 From: keepgogogo <57135073+keepgogogo@users.noreply.github.com> Date: Wed, 13 Dec 2023 19:04:26 +0800 Subject: [PATCH 22/59] =?UTF-8?q?0017.=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81?= =?UTF-8?q?=E7=9A=84=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88=E7=9A=84Java?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=B3=A8=E9=87=8A=E4=B8=AD=E5=B0=86StringBui?= =?UTF-8?q?lder=E5=86=99=E6=88=90=E4=BA=86StringBuild?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 90296efd..076bb771 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -260,7 +260,7 @@ class Solution { } - //每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild + //每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuilder StringBuilder temp = new StringBuilder(); //比如digits如果为"23",num 为0,则str表示2对应的 abc From dcc37da6034f3ad8166c9f06ee2ab75a3ad204e7 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 14 Dec 2023 10:01:34 +0800 Subject: [PATCH 23/59] =?UTF-8?q?Update0039.=E7=BB=84=E5=90=88=E7=BB=BC?= =?UTF-8?q?=E5=90=88=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index 37d5614e..81558cc1 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -598,6 +598,66 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum(int[] candidates, int target) + { + BackTracking(candidates, target, 0, 0); + return res; + } + public void BackTracking(int[] candidates, int target, int start, int sum) + { + if (sum > target) return; + if (sum == target) + { + res.Add(new List(path)); + return; + } + for (int i = start; i < candidates.Length; i++) + { + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} + +// 剪枝优化 +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> CombinationSum(int[] candidates, int target) + { + Array.Sort(candidates); + BackTracking(candidates, target, 0, 0); + return res; + } + public void BackTracking(int[] candidates, int target, int start, int sum) + { + if (sum > target) return; + if (sum == target) + { + res.Add(new List(path)); + return; + } + for (int i = start; i < candidates.Length && sum + candidates[i] <= target; i++) + { + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} +```

From dd287478a1eaa1b2110a12775b3f72f77e9ed23a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=84=E6=B7=B1=E8=80=81=E8=90=8C=E6=96=B0?= <98251397+Kiro-Young@users.noreply.github.com> Date: Thu, 14 Dec 2023 14:50:53 +0800 Subject: [PATCH 24/59] =?UTF-8?q?Fix:=20=E4=BF=AE=E6=AD=A3=E6=A0=88?= =?UTF-8?q?=E4=B8=8E=E9=98=9F=E5=88=97=E6=80=BB=E7=BB=93.md=E7=9A=84?= =?UTF-8?q?=E4=B8=80=E5=A4=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 修正一处栈与队列总结.md的错别字,“本地”应该为“本题” --- problems/栈与队列总结.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/栈与队列总结.md b/problems/栈与队列总结.md index 4e08a887..06a78270 100644 --- a/problems/栈与队列总结.md +++ b/problems/栈与队列总结.md @@ -115,7 +115,7 @@ cd a/b/c/../../ **单调队列不是一成不变的,而是不同场景不同写法**,总之要保证队列里单调递减或递增的原则,所以叫做单调队列。 -**不要以为本地中的单调队列实现就是固定的写法。** +**不要以为本题中的单调队列实现就是固定的写法。** 我们用deque作为单调队列的底层数据结构,C++中deque是stack和queue默认的底层实现容器(这个我们之前已经讲过),deque是可以两边扩展的,而且deque里元素并不是严格的连续分布的。 From a9ed0d367200a4e85eed5f93a728fbed0f7f7b5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=84=E6=B7=B1=E8=80=81=E8=90=8C=E6=96=B0?= <98251397+Kiro-Young@users.noreply.github.com> Date: Thu, 14 Dec 2023 14:59:16 +0800 Subject: [PATCH 25/59] =?UTF-8?q?Fix:=200347.=E5=89=8DK=E4=B8=AA=E9=AB=98?= =?UTF-8?q?=E9=A2=91=E5=85=83=E7=B4=A0.md=20Java=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E9=A3=8E=E6=A0=BC=E8=A7=84=E8=8C=83=E6=94=B9?= =?UTF-8?q?=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix: 0347.前K个高频元素.md Java部分代码风格规范改进;今天看示例代码觉得有点挤得难受,仔细看发现是未简化的讲解部分代码不少地方缺空格太拥挤,所以前来加一些空格便于阅读,未修改代码及其逻辑,仅方便阅读改进代码风格添加了些许空格 --- problems/0347.前K个高频元素.md | 48 ++++++++++++++-------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 4830f9a3..94b29eba 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -145,43 +145,43 @@ public: class Solution { //解法1:基于大顶堆实现 public int[] topKFrequent1(int[] nums, int k) { - Map map = new HashMap<>();//key为数组元素值,val为对应出现次数 - for(int num:nums){ - map.put(num,map.getOrDefault(num,0)+1); + Map map = new HashMap<>(); //key为数组元素值,val为对应出现次数 + for (int num : nums) { + map.put(num, map.getOrDefault(num,0) + 1); } - //在优先队列中存储二元组(num,cnt),cnt表示元素值num在数组中的出现次数 + //在优先队列中存储二元组(num, cnt),cnt表示元素值num在数组中的出现次数 //出现次数按从队头到队尾的顺序是从大到小排,出现次数最多的在队头(相当于大顶堆) - PriorityQueue pq = new PriorityQueue<>((pair1, pair2)->pair2[1]-pair1[1]); - for(Map.Entry entry:map.entrySet()){//大顶堆需要对所有元素进行排序 - pq.add(new int[]{entry.getKey(),entry.getValue()}); + PriorityQueue pq = new PriorityQueue<>((pair1, pair2) -> pair2[1] - pair1[1]); + for (Map.Entry entry : map.entrySet()) {//大顶堆需要对所有元素进行排序 + pq.add(new int[]{entry.getKey(), entry.getValue()}); } int[] ans = new int[k]; - for(int i=0;i map = new HashMap<>();//key为数组元素值,val为对应出现次数 - for(int num:nums){ - map.put(num,map.getOrDefault(num,0)+1); + Map map = new HashMap<>(); //key为数组元素值,val为对应出现次数 + for (int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); } - //在优先队列中存储二元组(num,cnt),cnt表示元素值num在数组中的出现次数 + //在优先队列中存储二元组(num, cnt),cnt表示元素值num在数组中的出现次数 //出现次数按从队头到队尾的顺序是从小到大排,出现次数最低的在队头(相当于小顶堆) - PriorityQueue pq = new PriorityQueue<>((pair1,pair2)->pair1[1]-pair2[1]); - for(Map.Entry entry:map.entrySet()){//小顶堆只需要维持k个元素有序 - if(pq.size()pq.peek()[1]){//当前元素出现次数大于小顶堆的根结点(这k个元素中出现次数最少的那个) - pq.poll();//弹出队头(小顶堆的根结点),即把堆里出现次数最少的那个删除,留下的就是出现次数多的了 - pq.add(new int[]{entry.getKey(),entry.getValue()}); + PriorityQueue pq = new PriorityQueue<>((pair1, pair2) -> pair1[1] - pair2[1]); + for (Map.Entry entry : map.entrySet()) { //小顶堆只需要维持k个元素有序 + if (pq.size() < k) { //小顶堆元素个数小于k个时直接加 + pq.add(new int[]{entry.getKey(), entry.getValue()}); + } else { + if (entry.getValue() > pq.peek()[1]) { //当前元素出现次数大于小顶堆的根结点(这k个元素中出现次数最少的那个) + pq.poll(); //弹出队头(小顶堆的根结点),即把堆里出现次数最少的那个删除,留下的就是出现次数多的了 + pq.add(new int[]{entry.getKey(), entry.getValue()}); } } } int[] ans = new int[k]; - for(int i=k-1;i>=0;i--){//依次弹出小顶堆,先弹出的是堆的根,出现次数少,后面弹出的出现次数多 + for (int i = k - 1; i >= 0; i--) { //依次弹出小顶堆,先弹出的是堆的根,出现次数少,后面弹出的出现次数多 ans[i] = pq.poll()[0]; } return ans; @@ -197,8 +197,8 @@ class Solution { PriorityQueue pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]); int[] res = new int[k]; // 答案数组为 k 个元素 Map map = new HashMap<>(); // 记录元素出现次数 - for(int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); - for(var x : map.entrySet()) { // entrySet 获取 k-v Set 集合 + for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); + for (var x : map.entrySet()) { // entrySet 获取 k-v Set 集合 // 将 kv 转化成数组 int[] tmp = new int[2]; tmp[0] = x.getKey(); @@ -209,7 +209,7 @@ class Solution { pq.poll(); } } - for(int i = 0; i < k; i ++) { + for (int i = 0; i < k; i++) { res[i] = pq.poll()[0]; // 获取优先队列里的元素 } return res; From 2cd982fd0dd478fb20989ee2dd8c1d28377f5829 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 15 Dec 2023 10:36:34 +0800 Subject: [PATCH 26/59] =?UTF-8?q?Update0040.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8C2=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 33e4a46f..994b04b8 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -773,7 +773,39 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public List> res = new List>(); + public List path = new List(); + public IList> CombinationSum2(int[] candidates, int target) + { + Array.Sort(candidates); + BackTracking(candidates, target, 0, 0); + return res; + } + public void BackTracking(int[] candidates, int target, int start, int sum) + { + if (sum > target) return; + if (sum == target) + { + res.Add(new List(path)); + return; + } + for (int i = start; i < candidates.Length && sum + candidates[i] <= target; i++) + { + if (i > start && candidates[i] == candidates[i - 1]) continue; + sum += candidates[i]; + path.Add(candidates[i]); + BackTracking(candidates, target, i + 1, sum); + sum -= candidates[i]; + path.RemoveAt(path.Count - 1); + } + } +} +```

From ed62561bc0c2e132380a2c5a548a87ad1461db3a Mon Sep 17 00:00:00 2001 From: RelishCoding <122661763+RelishCoding@users.noreply.github.com> Date: Fri, 15 Dec 2023 20:18:40 +0800 Subject: [PATCH 27/59] =?UTF-8?q?=E4=BC=98=E5=8C=96Java=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E6=BB=9A=E5=8A=A8=E6=95=B0=E7=BB=84=E8=A7=A3=E6=B3=95=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 个人觉得原解法中有冗余代码,具体原因一开始放issue里了:https://github.com/youngyangyang04/leetcode-master/issues/2364 --- problems/0494.目标和.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 1a4dda2b..2d38b4d0 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -275,19 +275,23 @@ class Solution { public int findTargetSumWays(int[] nums, int target) { int sum = 0; for (int i = 0; i < nums.length; i++) sum += nums[i]; - //如果target过大 sum将无法满足 - if ( target < 0 && sum < -target) return 0; - if ((target + sum) % 2 != 0) return 0; - int size = (target + sum) / 2; - if(size < 0) size = -size; - int[] dp = new int[size + 1]; + + //如果target的绝对值大于sum,那么是没有方案的 + if (Math.abs(target) > sum) return 0; + //如果(target+sum)除以2的余数不为0,也是没有方案的 + if ((target + sum) % 2 == 1) return 0; + + int bagSize = (target + sum) / 2; + int[] dp = new int[bagSize + 1]; dp[0] = 1; + for (int i = 0; i < nums.length; i++) { - for (int j = size; j >= nums[i]; j--) { + for (int j = bagSize; j >= nums[i]; j--) { dp[j] += dp[j - nums[i]]; } } - return dp[size]; + + return dp[bagSize]; } } ``` From 69a38ff1d30e4eb245f6dcebf5c5d177b08e3ea4 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 16 Dec 2023 09:26:57 +0800 Subject: [PATCH 28/59] =?UTF-8?q?Update0131.=E5=88=86=E5=89=B2=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 80ac2843..1d230ca8 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -847,6 +847,50 @@ object Solution { } } ``` +### CSharp +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> Partition(string s) + { + BackTracking(s, 0); + return res; + } + public void BackTracking(string s, int start) + { + if (start >= s.Length) + { + res.Add(new List(path)); + return; + } + + for (int i = start; i < s.Length; i++) + { + if (IsPalindrome(s, start, i)) + { + path.Add(s.Substring(start, i - start + 1)); + } + else + { + continue; + } + BackTracking(s, i + 1); + path.RemoveAt(path.Count - 1); + } + } + public bool IsPalindrome(string s, int start, int end) + { + for (int i = start, j = end; i < j; i++, j--) + { + if (s[i] != s[j]) + return false; + } + return true; + } +} +```

From 1675ea6fbee7adb3b1aefd20ea4cb9aa7ff23232 Mon Sep 17 00:00:00 2001 From: HQWQF <47740975+HQWQF@users.noreply.github.com> Date: Sat, 16 Dec 2023 16:57:54 +0800 Subject: [PATCH 29/59] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?.md=20=E4=BF=AE=E5=A4=8D=E6=B2=A1=E6=9C=89delete=20dummyHead?= =?UTF-8?q?=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit new了一个虚拟头结点,但没有delete它 --- problems/0024.两两交换链表中的节点.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 57034f47..405f4183 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -63,7 +63,9 @@ public: cur = cur->next->next; // cur移动两位,准备下一轮交换 } - return dummyHead->next; + ListNode* result = dummyHead->next; + delete dummyHead; + return result; } }; ``` From 32843da4dc1ed914ff5e030e1c09fd4d76b0ff73 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 17 Dec 2023 09:49:30 +0800 Subject: [PATCH 30/59] =?UTF-8?q?Update0093.=E5=A4=8D=E5=8E=9FIP=E5=9C=B0?= =?UTF-8?q?=E5=9D=80=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 59cd92da..c662957a 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -799,6 +799,53 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public IList res = new List(); + public IList RestoreIpAddresses(string s) + { + if (s.Length < 4 || s.Length > 12) return res; + BackTracking(s, 0, 0); + return res; + } + public void BackTracking(string s, int start, int pointSum) + { + if (pointSum == 3) + { + if (IsValid(s, start, s.Length - 1)) + { + res.Add(s); + } + return; + } + for (int i = start; i < s.Length; i++) + { + if (IsValid(s, start, i)) + { + s = s.Insert(i + 1, "."); + BackTracking(s, i + 2, pointSum + 1); + s = s.Remove(i + 1, 1); + } + else break; + } + } + public bool IsValid(string s, int start, int end) + { + if (start > end) return false; + if (s[start] == '0' && start != end) return false; + int num = 0; + for (int i = start; i <= end; i++) + { + if (s[i] > '9' || s[i] < '0') return false; + num = num * 10 + s[i] - '0'; + if (num > 255) return false; + } + return true; + } +} +```

From 2d92b509e0689ce90e4460578de9772a459d3092 Mon Sep 17 00:00:00 2001 From: keepgogogo <57135073+keepgogogo@users.noreply.github.com> Date: Sun, 17 Dec 2023 14:00:00 +0800 Subject: [PATCH 31/59] =?UTF-8?q?=E5=9B=9E=E6=BA=AF=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E7=AF=87=209=20=E5=88=86=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2?= =?UTF-8?q?=EF=BC=8CJava=E9=A2=98=E8=A7=A3=E7=A4=BA=E4=BE=8B=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=8F=90=E4=BE=9B=E4=BD=BF=E7=94=A8=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=E4=BC=98=E5=8C=96=E5=9B=9E=E6=96=87=E4=B8=B2?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E7=9A=84=E5=AE=9E=E7=8E=B0=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 1d230ca8..ca342d4b 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -349,6 +349,65 @@ class Solution { } ``` +### Java +回溯+动态规划优化回文串判断 +```Java +class Solution { + List> result; + LinkedList path; + boolean[][] dp; + + public List> partition(String s) { + result = new ArrayList<>(); + char[] str = s.toCharArray(); + path = new LinkedList<>(); + dp = new boolean[str.length + 1][str.length + 1]; + isPalindrome(str); + backtracking(s, 0); + return result; + } + + public void backtracking(String str, int startIndex) { + if (startIndex >= str.length()) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + result.add(new ArrayList<>(path)); + } else { + for (int i = startIndex; i < str.length(); ++i) { + if (dp[startIndex][i]) { + //是回文子串,进入下一步递归 + //先将当前子串保存入path + path.addLast(str.substring(startIndex, i + 1)); + //起始位置后移,保证不重复 + backtracking(str, i + 1); + path.pollLast(); + } else { + //不是回文子串,跳过 + continue; + } + } + } + } + + //通过动态规划判断是否是回文串,参考动态规划篇 52 回文子串 + public void isPalindrome(char[] str) { + for (int i = 0; i <= str.length; ++i) { + dp[i][i] = true; + } + for (int i = 1; i < str.length; ++i) { + for (int j = i; j >= 0; --j) { + if (str[j] == str[i]) { + if (i - j <= 1) { + dp[j][i] = true; + } else if (dp[j + 1][i - 1]) { + dp[j][i] = true; + } + } + } + } + } +} +``` + ### Python 回溯 基本版 ```python From 5b5a05ada59333813312ebfe2f3f258cb9ea791f Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 18 Dec 2023 09:23:42 +0800 Subject: [PATCH 32/59] =?UTF-8?q?Update0078.=E5=AD=90=E9=9B=86=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 5f3654de..06547e3d 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -443,6 +443,27 @@ object Solution { } } ``` +### C# +```csharp +public class Solution { + public IList> res = new List>(); + public IList path = new List(); + public IList> Subsets(int[] nums) { + BackTracking(nums, 0); + return res; + } + public void BackTracking(int[] nums, int start){ + res.Add(new List(path)); + if(start > nums.Length) return; + for (int i = start; i < nums.Length; i++) + { + path.Add(nums[i]); + BackTracking(nums, i + 1); + path.RemoveAt(path.Count - 1); + } + } +} +```

From 7fdb7b17024bbfd7636dbc8100acb1687445b40b Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 19 Dec 2023 09:32:06 +0800 Subject: [PATCH 33/59] =?UTF-8?q?Update0090.=E5=AD=90=E9=9B=862=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 13080cd9..9fc334a4 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -640,6 +640,31 @@ object Solution { } } ``` +### C# +```c# +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> SubsetsWithDup(int[] nums) + { + Array.Sort(nums); + BackTracking(nums, 0); + return res; + } + public void BackTracking(int[] nums, int start) + { + res.Add(new List(path)); + for (int i = start; i < nums.Length; i++) + { + if (i > start && nums[i] == nums[i - 1]) continue; + path.Add(nums[i]); + BackTracking(nums, i + 1); + path.RemoveAt(path.Count - 1); + } + } +} +```

From f9342095c9b7d79d8c6debc165a193ddc3e39169 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 20 Dec 2023 09:26:14 +0800 Subject: [PATCH 34/59] =?UTF-8?q?Update0491.=E9=80=92=E5=A2=9E=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index eb0be005..1aa69a36 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -614,6 +614,32 @@ object Solution { } } ``` +### C# +```csharp +public class Solution { + public IList> res = new List>(); + public IList path = new List(); + public IList> FindSubsequences(int[] nums) { + BackTracking(nums, 0); + return res; + } + public void BackTracking(int[] nums, int start){ + if(path.Count >= 2){ + res.Add(new List(path)); + } + HashSet hs = new HashSet(); + for(int i = start; i < nums.Length; i++){ + if(path.Count > 0 && path[path.Count - 1] > nums[i] || hs.Contains(nums[i])){ + continue; + } + hs.Add(nums[i]); + path.Add(nums[i]); + BackTracking(nums, i + 1); + path.RemoveAt(path.Count - 1); + } + } +} +```

From 4ee74f12892497dce83ba6a2d7c74056d2d9216b Mon Sep 17 00:00:00 2001 From: block <1181882120@qq.com> Date: Wed, 20 Dec 2023 18:11:23 +0800 Subject: [PATCH 35/59] Correction document statement --- problems/回溯算法理论基础.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/回溯算法理论基础.md b/problems/回溯算法理论基础.md index dff1823c..f22c67b1 100644 --- a/problems/回溯算法理论基础.md +++ b/problems/回溯算法理论基础.md @@ -65,7 +65,7 @@ **回溯法解决的问题都可以抽象为树形结构**,是的,我指的是所有回溯法的问题都可以抽象为树形结构! -因为回溯法解决的都是在集合中递归查找子集,**集合的大小就构成了树的宽度,递归的深度,都构成的树的深度**。 +因为回溯法解决的都是在集合中递归查找子集,**集合的大小就构成了树的宽度,递归的深度就构成了树的深度**。 递归就要有终止条件,所以必然是一棵高度有限的树(N叉树)。 From eff7a7a9b27cf76d530a253bdfb0b9824e768a3a Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 21 Dec 2023 09:36:09 +0800 Subject: [PATCH 36/59] =?UTF-8?q?Update0046.=E5=85=A8=E6=8E=92=E5=88=97?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 1f5263a7..15e6ae16 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -486,6 +486,37 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public IList> res = new List>(); + public IList path = new List(); + public IList> Permute(int[] nums) + { + var used = new bool[nums.Length]; + BackTracking(nums, used); + return res; + } + public void BackTracking(int[] nums, bool[] used) + { + if (path.Count == nums.Length) + { + res.Add(new List(path)); + return; + } + for (int i = 0; i < nums.Length; i++) + { + if (used[i]) continue; + used[i] = true; + path.Add(nums[i]); + BackTracking(nums, used); + used[i] = false; + path.RemoveAt(path.Count - 1); + } + } +} +```

From 25a330fcdbc4b2e6958efa51143ce31f476dc60a Mon Sep 17 00:00:00 2001 From: cherrypicker Date: Thu, 21 Dec 2023 15:29:18 +0800 Subject: [PATCH 37/59] =?UTF-8?q?Update0704.=E4=BA=8C=E5=88=86=E6=9F=A5?= =?UTF-8?q?=E6=89=BE=20Go=E7=A4=BA=E4=BE=8B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加注释、计算区间中点mid时使用位运算代替除法运算 --- problems/0704.二分查找.md | 72 ++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 26 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 590ec1b1..c3783aa3 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -251,40 +251,60 @@ class Solution: (版本一)左闭右闭区间 ```go +// 时间复杂度 O(logn) func search(nums []int, target int) int { - high := len(nums)-1 - low := 0 - for low <= high { - mid := low + (high-low)/2 - if nums[mid] == target { - return mid - } else if nums[mid] > target { - high = mid-1 - } else { - low = mid+1 - } - } - return -1 + // 初始化左右边界 + left := 0 + right := len(nums) - 1 + + // 循环逐步缩小区间范围 + for left <= right { + // 求区间中点 + mid := left + (right-left)>>1 + + // 根据 nums[mid] 和 target 的大小关系 + // 调整区间范围 + if nums[mid] == target { + return mid + } else if nums[mid] < target { + left = mid + 1 + } else { + right = mid - 1 + } + } + + // 在输入数组内没有找到值等于 target 的元素 + return -1 } ``` (版本二)左闭右开区间 ```go +// 时间复杂度 O(logn) func search(nums []int, target int) int { - high := len(nums) - low := 0 - for low < high { - mid := low + (high-low)/2 - if nums[mid] == target { - return mid - } else if nums[mid] > target { - high = mid - } else { - low = mid+1 - } - } - return -1 + // 初始化左右边界 + left := 0 + right := len(nums) + + // 循环逐步缩小区间范围 + for left < right { + // 求区间中点 + mid := left + (right-left)>>1 + + // 根据 nums[mid] 和 target 的大小关系 + // 调整区间范围 + if nums[mid] == target { + return mid + } else if nums[mid] < target { + left = mid + 1 + } else { + right = mid + } + } + + // 在输入数组内没有找到值等于 target 的元素 + return -1 } ``` From 4516aaab6096e84f5fd7b526a135225c1b862570 Mon Sep 17 00:00:00 2001 From: cherrypicker Date: Thu, 21 Dec 2023 15:36:44 +0800 Subject: [PATCH 38/59] =?UTF-8?q?Update0027.=E7=A7=BB=E9=99=A4=E5=85=83?= =?UTF-8?q?=E7=B4=A0=20Go=E7=A4=BA=E4=BE=8B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加注释、代码格式化 --- problems/0027.移除元素.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 8522e785..dbde3d19 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -256,17 +256,24 @@ class Solution: ### Go: ```go +// 快慢指针法 +// 时间复杂度 O(n) +// 空间复杂度 O(1) func removeElement(nums []int, val int) int { - length:=len(nums) - res:=0 - for i:=0;i Date: Thu, 21 Dec 2023 14:22:44 -0800 Subject: [PATCH 39/59] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Kama54.=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E6=95=B0=E5=AD=97=E7=9A=84Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama54.替换数字.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/problems/kama54.替换数字.md b/problems/kama54.替换数字.md index 0f8daa21..2b3d53de 100644 --- a/problems/kama54.替换数字.md +++ b/problems/kama54.替换数字.md @@ -235,7 +235,15 @@ func main(){ ### python: - +```Python +class Solution: + def change(self, s): + lst = list(s) # Python里面的string也是不可改的,所以也是需要额外空间的。空间复杂度:O(n)。 + for i in range(len(lst)): + if lst[i].isdigit(): + lst[i] = "number" + return ''.join(lst) +``` ### JavaScript: From 1fbe05532511a96e48b118172ed5f9e2f21ad7c6 Mon Sep 17 00:00:00 2001 From: cherrypicker Date: Fri, 22 Dec 2023 10:02:23 +0800 Subject: [PATCH 40/59] =?UTF-8?q?Update0232.=E7=94=A8=E6=A0=88=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E9=98=9F=E5=88=97=20=E4=BC=98=E5=8C=96Go=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用切片模拟栈的实现,即 MyStack --- problems/0232.用栈实现队列.md | 87 +++++++++++++++++++---------- 1 file changed, 56 insertions(+), 31 deletions(-) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 24374010..41933ca4 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -235,52 +235,77 @@ class MyQueue: ### Go: ```Go -type MyQueue struct { - stackIn []int //输入栈 - stackOut []int //输出栈 +// 通过切片实现一个栈 +// 由于只是辅助实现算法题目,因此不做异常情况处理 +type MyStack []int + +func (s *MyStack) Push(v int) { + *s = append(*s, v) } +func (s *MyStack) Pop() int { + val := (*s)[len(*s)-1] + *s = (*s)[:len(*s)-1] + return val +} + +func (s *MyStack) Peek() int { + return (*s)[len(*s)-1] +} + +func (s *MyStack) Size() int { + return len(*s) +} + +func (s *MyStack) Empty() bool { + return s.Size() == 0 +} + +// ---------- 分界线 ---------- + +type MyQueue struct { + stackIn *MyStack + stackOut *MyStack +} + + func Constructor() MyQueue { - return MyQueue{ - stackIn: make([]int, 0), - stackOut: make([]int, 0), + return MyQueue { + stackIn: &MyStack{}, + stackOut: &MyStack{}, } } -// 往输入栈做push -func (this *MyQueue) Push(x int) { - this.stackIn = append(this.stackIn, x) + +func (this *MyQueue) Push(x int) { + this.stackIn.Push(x) } -// 在输出栈做pop,pop时如果输出栈数据为空,需要将输入栈全部数据导入,如果非空,则可直接使用 + func (this *MyQueue) Pop() int { - inLen, outLen := len(this.stackIn), len(this.stackOut) - if outLen == 0 { - if inLen == 0 { - return -1 - } - for i := inLen - 1; i >= 0; i-- { - this.stackOut = append(this.stackOut, this.stackIn[i]) - } - this.stackIn = []int{} //导出后清空 - outLen = len(this.stackOut) //更新长度值 - } - val := this.stackOut[outLen-1] - this.stackOut = this.stackOut[:outLen-1] - return val + this.fillStackOut() + return this.stackOut.Pop() } + func (this *MyQueue) Peek() int { - val := this.Pop() - if val == -1 { - return -1 - } - this.stackOut = append(this.stackOut, val) - return val + this.fillStackOut() + return this.stackOut.Peek() } + func (this *MyQueue) Empty() bool { - return len(this.stackIn) == 0 && len(this.stackOut) == 0 + return this.stackIn.Empty() && this.stackOut.Empty() +} + +// fillStackOut 填充输出栈 +func (this *MyQueue) fillStackOut() { + if this.stackOut.Empty() { + for !this.stackIn.Empty() { + val := this.stackIn.Pop() + this.stackOut.Push(val) + } + } } ``` From f134c39c868c3b8a48389db6e11fe412904087b2 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 22 Dec 2023 10:17:21 +0800 Subject: [PATCH 41/59] =?UTF-8?q?Update=200047.=E5=85=A8=E6=8E=92=E5=88=97?= =?UTF-8?q?2=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0047.全排列II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index 4fed8a5c..7f2c3638 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -521,6 +521,38 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public List> res = new List>(); + public List path = new List(); + public IList> PermuteUnique(int[] nums) + { + Array.Sort(nums); + BackTracking(nums, new bool[nums.Length]); + return res; + } + public void BackTracking(int[] nums, bool[] used) + { + if (nums.Length == path.Count) + { + res.Add(new List(path)); + return; + } + for (int i = 0; i < nums.Length; i++) + { + if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue; + if (used[i]) continue; + path.Add(nums[i]); + used[i] = true; + BackTracking(nums, used); + path.RemoveAt(path.Count - 1); + used[i] = false; + } + } +} +```

From 9319ce9cdcab03027644ce1cff57b4060d53bc99 Mon Sep 17 00:00:00 2001 From: cherrypicker Date: Sat, 23 Dec 2023 08:34:38 +0800 Subject: [PATCH 42/59] =?UTF-8?q?Update0020.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E6=8B=AC=E5=8F=B7=20Go=E7=A4=BA=E4=BE=8B=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原有的实现已经足够简洁清晰,这个版本的代码增加了注释,提升了可读性。 --- problems/0020.有效的括号.md | 48 ++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 045c79ee..17fbe2be 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -218,23 +218,41 @@ class Solution: ### Go: ```Go +// 思路: 使用栈来进行括号的匹配 +// 时间复杂度 O(n) +// 空间复杂度 O(n) func isValid(s string) bool { - hash := map[byte]byte{')':'(', ']':'[', '}':'{'} - stack := make([]byte, 0) - if s == "" { - return true - } + // 使用切片模拟栈的行为 + stack := make([]rune, 0) - for i := 0; i < len(s); i++ { - if s[i] == '(' || s[i] == '[' || s[i] == '{' { - stack = append(stack, s[i]) - } else if len(stack) > 0 && stack[len(stack)-1] == hash[s[i]] { - stack = stack[:len(stack)-1] - } else { - return false - } - } - return len(stack) == 0 + // m 用于记录某个右括号对应的左括号 + m := make(map[rune]rune) + m[')'] = '(' + m[']'] = '[' + m['}'] = '{' + + // 遍历字符串中的 rune + for _, c := range s { + // 左括号直接入栈 + if c == '(' || c == '[' || c == '{' { + stack = append(stack, c) + } else { + // 如果是右括号,先判断栈内是否还有元素 + if len(stack) == 0 { + return false + } + // 再判断栈顶元素是否能够匹配 + peek := stack[len(stack)-1] + if peek != m[c] { + return false + } + // 模拟栈顶弹出 + stack = stack[:len(stack)-1] + } + } + + // 若栈中不再包含元素,则能完全匹配 + return len(stack) == 0 } ``` From 69103f6c86fddc3d10ffe921dce8b93e259f71e2 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 23 Dec 2023 10:11:06 +0800 Subject: [PATCH 43/59] =?UTF-8?q?Update0051.N=E7=9A=87=E5=90=8E=EF=BC=8C?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index f6290793..1e108540 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -865,6 +865,60 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public List> res = new(); + public IList> SolveNQueens(int n) + { + char[][] chessBoard = new char[n][]; + for (int i = 0; i < n; i++) + { + chessBoard[i] = new char[n]; + for (int j = 0; j < n; j++) + { + chessBoard[i][j] = '.'; + } + } + BackTracking(n, 0, chessBoard); + return res; + } + public void BackTracking(int n, int row, char[][] chessBoard) + { + if (row == n) + { + res.Add(chessBoard.Select(x => new string(x)).ToList()); + return; + } + for (int col = 0; col < n; col++) + { + if (IsValid(row, col, chessBoard, n)) + { + chessBoard[row][col] = 'Q'; + BackTracking(n, row + 1, chessBoard); + chessBoard[row][col] = '.'; + } + } + } + public bool IsValid(int row, int col, char[][] chessBoard, int n) + { + for (int i = 0; i < row; i++) + { + if (chessBoard[i][col] == 'Q') return false; + } + for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) + { + if (chessBoard[i][j] == 'Q') return false; + } + for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) + { + if (chessBoard[i][j] == 'Q') return false; + } + return true; + } +} +```

From 3bd387df7cde50b6fada28aa824841f4c842921d Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 24 Dec 2023 09:42:46 +0800 Subject: [PATCH 44/59] =?UTF-8?q?Update0037.=E8=A7=A3=E6=95=B0=E7=8B=AC?= =?UTF-8?q?=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0037.解数独.md | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 1763063e..d96e59df 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -756,6 +756,59 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public void SolveSudoku(char[][] board) + { + BackTracking(board); + } + public bool BackTracking(char[][] board) + { + for (int i = 0; i < board.Length; i++) + { + for (int j = 0; j < board[0].Length; j++) + { + if (board[i][j] != '.') continue; + for (char k = '1'; k <= '9'; k++) + { + if (IsValid(board, i, j, k)) + { + board[i][j] = k; + if (BackTracking(board)) return true; + board[i][j] = '.'; + } + } + return false; + } + + } + return true; + } + public bool IsValid(char[][] board, int row, int col, char val) + { + for (int i = 0; i < 9; i++) + { + if (board[i][col] == val) return false; + } + for (int i = 0; i < 9; i++) + { + if (board[row][i] == val) return false; + } + int startRow = (row / 3) * 3; + int startCol = (col / 3) * 3; + for (int i = startRow; i < startRow + 3; i++) + { + for (int j = startCol; j < startCol + 3; j++) + { + if (board[i][j] == val) return false; + } + } + return true; + } +} +```

From 689c086f3a4094e3eeb5e639b69126c29b626561 Mon Sep 17 00:00:00 2001 From: ZhangLiPeng <2353375282@qq.com> Date: Sun, 24 Dec 2023 14:44:08 +0800 Subject: [PATCH 45/59] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E6=80=BB=E7=BB=93=E7=AF=87.md=20=E7=9A=84=E6=96=87=E5=AD=97?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= 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 3f2f5c97..72d2b7ad 100644 --- a/problems/链表总结篇.md +++ b/problems/链表总结篇.md @@ -22,7 +22,7 @@ ### 虚拟头结点 -在[链表:听说用虚拟头节点会方便很多?](https://programmercarl.com/0203.移除链表元素.html)中,我们讲解了链表操作中一个非常总要的技巧:虚拟头节点。 +在[链表:听说用虚拟头节点会方便很多?](https://programmercarl.com/0203.移除链表元素.html)中,我们讲解了链表操作中一个非常重要的技巧:虚拟头节点。 链表的一大问题就是操作当前节点必须要找前一个节点才能操作。这就造成了,头结点的尴尬,因为头结点没有前一个节点了。 From 5fd8c8e6a7d2c8a5f25a0c5aaa0a942f1be3a24f Mon Sep 17 00:00:00 2001 From: ZhangLiPeng <2353375282@qq.com> Date: Sun, 24 Dec 2023 17:10:16 +0800 Subject: [PATCH 46/59] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E6=80=BB=E7=BB=93=E7=AF=87.md=20=E7=9A=84=E6=96=87=E5=AD=97?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1?= 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 72d2b7ad..b2b1b779 100644 --- a/problems/链表总结篇.md +++ b/problems/链表总结篇.md @@ -32,7 +32,7 @@ ### 链表的基本操作 -在[链表:一道题目考察了常见的五个操作!](https://programmercarl.com/0707.设计链表.html)中,我们通设计链表把链表常见的五个操作练习了一遍。 +在[链表:一道题目考察了常见的五个操作!](https://programmercarl.com/0707.设计链表.html)中,我们通过设计链表把链表常见的五个操作练习了一遍。 这是练习链表基础操作的非常好的一道题目,考察了: From 9cea1567fe338ec4842276c4e27e9d4933893bd3 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 25 Dec 2023 09:35:23 +0800 Subject: [PATCH 47/59] =?UTF-8?q?Update0455.=E5=88=86=E5=8F=91=E9=A5=BC?= =?UTF-8?q?=E5=B9=B2=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index c9c1a852..778adc94 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -378,6 +378,28 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int FindContentChildren(int[] g, int[] s) + { + Array.Sort(g); + Array.Sort(s); + int index = s.Length - 1; + int res = 0; + for (int i = g.Length - 1; i >=0; i--) + { + if(index >=0 && s[index]>=g[i]) + { + res++; + index--; + } + } + return res; + } +} +```

From 95e8b279aef0dab41fce7210ad4f80fd74f8dca8 Mon Sep 17 00:00:00 2001 From: markwang Date: Mon, 25 Dec 2023 15:36:54 +0800 Subject: [PATCH 48/59] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b27a231e..08d25080 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -48,7 +48,7 @@ 在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢? -因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。 +因为是有序树,所以 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。 那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,**一定是最近公共祖先吗**? @@ -328,27 +328,34 @@ class Solution: ``` ### Go -递归法: +递归法 ```go func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { - if root == nil { - return nil - } - for { - if root.Val > p.Val && root.Val > q.Val { - root = root.Left - } - if root.Val < p.Val && root.Val < q.Val { - root = root.Right - } - if (root.Val - p.Val) * (root.Val - q.Val) <= 0 { - return root - } - } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } else if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } else { return root + } } ``` +迭代法 +```go +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for root != nil { + if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else { + return root + } + } + return nil +} +``` ### JavaScript From b22425c859269c5862149a8f736bcf0c3e5e00eb Mon Sep 17 00:00:00 2001 From: Relsola Date: Mon, 25 Dec 2023 22:55:12 +0800 Subject: [PATCH 49/59] =?UTF-8?q?Update=200084.=E6=9F=B1=E7=8A=B6=E5=9B=BE?= =?UTF-8?q?=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84=E7=9F=A9=E5=BD=A2=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E5=90=8D=E9=94=99=E8=AF=AF=E4=BF=AE=E5=A4=8D=E5=92=8C?= =?UTF-8?q?=E5=8F=AF=E8=AF=BB=E6=80=A7=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0084.柱状图中最大的矩形.md | 66 ++++++++++++-------- 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index 97dab4f3..b836705a 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -515,27 +515,31 @@ func largestRectangleArea(heights []int) int { var largestRectangleArea = function(heights) { const len = heights.length; const minLeftIndex = new Array(len); - const maxRigthIndex = new Array(len); + const maxRightIndex = new Array(len); // 记录每个柱子 左边第一个小于该柱子的下标 minLeftIndex[0] = -1; // 注意这里初始化,防止下面while死循环 for(let i = 1; i < len; i++) { let t = i - 1; // 这里不是用if,而是不断向左寻找的过程 - while(t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t]; + while (t >= 0 && heights[t] >= heights[i]) { + t = minLeftIndex[t]; + } minLeftIndex[i] = t; } // 记录每个柱子 右边第一个小于该柱子的下标 - maxRigthIndex[len - 1] = len; // 注意这里初始化,防止下面while死循环 + maxRightIndex[len - 1] = len; // 注意这里初始化,防止下面while死循环 for(let i = len - 2; i >= 0; i--){ let t = i + 1; // 这里不是用if,而是不断向右寻找的过程 - while(t < len && heights[t] >= heights[i]) t = maxRigthIndex[t]; - maxRigthIndex[i] = t; + while (t <= n && heights[t] > heights[i]) { + t = maxRightIndex[t]; + } + maxRightIndex[i] = t; } // 求和 let maxArea = 0; for(let i = 0; i < len; i++){ - let sum = heights[i] * (maxRigthIndex[i] - minLeftIndex[i] - 1); + let sum = heights[i] * (maxRightIndex[i] - minLeftIndex[i] - 1); maxArea = Math.max(maxArea , sum); } return maxArea; @@ -543,27 +547,37 @@ var largestRectangleArea = function(heights) { //单调栈 var largestRectangleArea = function(heights) { - let maxArea = 0; - const stack = []; - heights = [0,...heights,0]; // 数组头部加入元素0 数组尾部加入元素0 - for(let i = 0; i < heights.length; i++){ - if(heights[i] > heights[stack[stack.length-1]]){ // 情况三 - stack.push(i); - } else if(heights[i] === heights[stack[stack.length-1]]){ // 情况二 - stack.pop(); // 这个可以加,可以不加,效果一样,思路不同 - stack.push(i); - } else { // 情况一 - while(heights[i] < heights[stack[stack.length-1]]){// 当前bar比栈顶bar矮 - const stackTopIndex = stack.pop();// 栈顶元素出栈,并保存栈顶bar的索引 - let w = i - stack[stack.length -1] - 1; - let h = heights[stackTopIndex] + let maxArea = 0; + const stack = [0]; + heights.push(0); + const n = heights.length; + + for (let i = 1; i < n; i++) { + let top = stack.at(-1); + // 情况三 + if (heights[top] < heights[i]) { + stack.push(i); + } + // 情况二 + if (heights[top] === heights[i]) { + stack.pop(); // 这个可以加,可以不加,效果一样,思路不同 + stack.push(i); + } + // 情况一 + if (heights[top] > heights[i]) { + while (stack.length > 0 && heights[top] > heights[i]) { + // 栈顶元素出栈,并保存栈顶bar的索引 + const h = heights[stack.pop()]; + const left = stack.at(-1) ?? -1; + const w = i - left - 1; // 计算面积,并取最大面积 - maxArea = Math.max(maxArea, w * h); - } - stack.push(i);// 当前bar比栈顶bar高了,入栈 - } - } - return maxArea; + maxArea = Math.max(maxArea, w * h); + top = stack.at(-1); + } + stack.push(i); + } + } + return maxArea; }; //单调栈 简洁 From b01155fbf24ee11b8a45aa9b7e0f67f2398509c2 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 26 Dec 2023 09:11:30 +0800 Subject: [PATCH 50/59] =?UTF-8?q?docs:=E4=BF=AE=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/0376.摆动序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 5203d7d6..ceea31fe 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -64,7 +64,7 @@ 在计算是否有峰值的时候,大家知道遍历的下标 i ,计算 prediff(nums[i] - nums[i-1]) 和 curdiff(nums[i+1] - nums[i]),如果`prediff < 0 && curdiff > 0` 或者 `prediff > 0 && curdiff < 0` 此时就有波动就需要统计。 -这是我们思考本题的一个大题思路,但本题要考虑三种情况: +这是我们思考本题的一个大体思路,但本题要考虑三种情况: 1. 情况一:上下坡中有平坡 2. 情况二:数组首尾两端 From 7924803206a0dc2b06b6d6f3c7281d9f56970a71 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 26 Dec 2023 09:12:03 +0800 Subject: [PATCH 51/59] =?UTF-8?q?Update0376.=E6=91=86=E5=8A=A8=E5=BA=8F?= =?UTF-8?q?=E5=88=97=EF=BC=8C=E6=B7=BB=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index ceea31fe..5c2241c8 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -692,6 +692,27 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int WiggleMaxLength(int[] nums) + { + if (nums.Length < 2) return nums.Length; + int curDiff = 0, preDiff = 0, res = 1; + for (int i = 0; i < nums.Length - 1; i++) + { + curDiff = nums[i + 1] - nums[i]; + if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) + { + res++; + preDiff = curDiff; + } + } + return res; + } +} +```

From 54c3a74618182fc480334e1105bc3030948e208d Mon Sep 17 00:00:00 2001 From: block <1181882120@qq.com> Date: Tue, 26 Dec 2023 10:52:24 +0800 Subject: [PATCH 52/59] Update max array doc --- problems/1005.K次取反后最大化的数组和.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index bed11c7a..27cabdc5 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -16,7 +16,7 @@ 示例 1: * 输入:A = [4,2,3], K = 1 * 输出:5 -* 解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。 +* 解释:选择索引 (1) ,然后 A 变为 [4,-2,3]。 示例 2: * 输入:A = [3,-1,0,2], K = 3 From a937b7674623ecbbe24e61d20d6af7d771ab6304 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 27 Dec 2023 09:49:34 +0800 Subject: [PATCH 53/59] =?UTF-8?q?Update0053.=E6=9C=80=E5=A4=A7=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=92=8C=EF=BC=8C=E6=B7=BB=E5=8A=A0C#=E8=B4=AA?= =?UTF-8?q?=E5=BF=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 639c54bc..78c8b382 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -406,6 +406,26 @@ object Solution { } } ``` +### C# +**贪心** +```csharp +public class Solution +{ + public int MaxSubArray(int[] nums) + { + int res = Int32.MinValue; + int count = 0; + for (int i = 0; i < nums.Length; i++) + { + count += nums[i]; + res = Math.Max(res, count); + if (count < 0) count = 0; + } + return res; + } +} +``` +

From 2368a622773736ee74f8d432f8cb891ec2f3c74c Mon Sep 17 00:00:00 2001 From: Relsola Date: Wed, 27 Dec 2023 19:23:37 +0800 Subject: [PATCH 54/59] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E6=B7=B1=E6=90=9C=E7=89=88.md=20=E6=96=B0=E5=A2=9ETS?= =?UTF-8?q?=E6=B7=B1=E5=BA=A6=E6=90=9C=E7=B4=A2=E4=BC=98=E5=85=88=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.深搜版.md | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index 43eb66e1..a4b93c3d 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -346,6 +346,46 @@ var numIslands = function (grid) { }; ``` +### TypeScript + +```TypeScript +function numIslands(grid: string[][]): number { + // 四个方向 + const dir: number[][] = [[0, 1], [1, 0], [-1, 0], [0, -1]]; + const [m, n]: [number, number] = [grid.length, grid[0].length]; + + function dfs(grid: string[][], visited: boolean[][], x: number, y: number) { + for (let i = 0; i < 4; i++) { + let nextX: number = x + dir[i][0]; + let nextY: number = y + dir[i][1]; + // 越界了,直接跳过 + if (nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) { + continue; + } + // 没有访问过同时是陆地 + if (!visited[nextX][nextY] && grid[nextX][nextY] === '1') { + visited[nextX][nextY] = true; + dfs(grid, visited, nextX, nextY); + } + } + } + + const visited: boolean[][] = Array.from({ length: m }, _ => new Array(n).fill(false)); + + let result: number = 0; + for (let i = 0; i < m; i++) { + for (let k = 0; k < n; k++) { + if (!visited[i][k] && grid[i][k] === '1') { + ++result; // 遇到没访问过的陆地,+1 + visited[i][k] = true; + dfs(grid, visited, i, k); // 将与其链接的陆地都标记上 true + } + } + } + return result; +} +``` + ### Go ```go From 22ebe65604be3b53c53503f64d1aa7ed3b0b220f Mon Sep 17 00:00:00 2001 From: Relsola Date: Wed, 27 Dec 2023 19:51:37 +0800 Subject: [PATCH 55/59] =?UTF-8?q?Update=20200.=E5=B2=9B=E5=B1=BF=E6=95=B0?= =?UTF-8?q?=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index e8ed60db..a7dd117b 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -276,6 +276,52 @@ var numIslands = function (grid) { }; ``` +### TypeScript + +```TypeScript +function numIslands2(grid: string[][]): number { + // 四个方向 + const dir: number[][] = [[0, 1], [1, 0], [-1, 0], [0, -1]]; + const [m, n]: [number, number] = [grid.length, grid[0].length]; + + function dfs(grid: string[][], visited: boolean[][], x: number, y: number) { + const queue: number[][] = [[x, y]]; + while (queue.length !== 0) { + //取出队列头部元素 + const top: number[] = queue.shift()!; + for (let i = 0; i < 4; i++) { + const nextX: number = top[0] + dir[i][0]; + const nextY: number = top[1] + dir[i][1]; + // 越界了,直接跳过 + if (nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) { + continue; + } + if (!visited[nextX][nextY] && grid[nextX][nextY] === '1') { + queue.push([nextX, nextY]); + // 只要加入队列立刻标记 + visited[nextX][nextY] = true; + } + } + } + } + + const visited: boolean[][] = Array.from({ length: m }, _ => new Array(n).fill(false)); + + let result = 0; + for (let i = 0; i < m; i++) { + for (let k = 0; k < n; k++) { + if (!visited[i][k] && grid[i][k] === '1') { + ++result; // 遇到没访问过的陆地,+1 + visited[i][k] = true; + dfs(grid, visited, i, k); // 将与其链接的陆地都标记上 true + } + } + } + return result; +} +``` + + ### Rust ```rust From c0c03a88831bc6b1ed20e8cedb068cec7e624181 Mon Sep 17 00:00:00 2001 From: ENJOY <954395302@qq.com> Date: Thu, 28 Dec 2023 16:03:23 +0800 Subject: [PATCH 56/59] =?UTF-8?q?0704.=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE?= =?UTF-8?q?.md=EF=BC=9A=E4=BF=AE=E6=94=B9=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/0704.二分查找.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index c3783aa3..31e89ae3 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -2,7 +2,7 @@ -

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

+

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

# 704. 二分查找 From b997d8108cd8fcf7b00e4b073f301f0bb9c447d2 Mon Sep 17 00:00:00 2001 From: ENJOY <954395302@qq.com> Date: Thu, 28 Dec 2023 16:49:49 +0800 Subject: [PATCH 57/59] =?UTF-8?q?=E5=85=B3=E4=BA=8E=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=EF=BC=8C=E4=BD=A0=E4=B8=8D=E7=9F=A5?= =?UTF-8?q?=E9=81=93=E7=9A=84=E9=83=BD=E5=9C=A8=E8=BF=99=E9=87=8C=EF=BC=81?= =?UTF-8?q?.md=EF=BC=9A=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...复杂度,你不知道的都在这里!.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/problems/关于时间复杂度,你不知道的都在这里!.md b/problems/关于时间复杂度,你不知道的都在这里!.md index d212e8be..a1e553d0 100644 --- a/problems/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/关于时间复杂度,你不知道的都在这里!.md @@ -10,7 +10,7 @@ **时间复杂度是一个函数,它定性描述该算法的运行时间**。 -我们在软件开发中,时间复杂度就是用来方便开发者估算出程序运行的答题时间。 +我们在软件开发中,时间复杂度就是用来方便开发者估算出程序运行的大体时间。 那么该如何估计程序运行时间呢,通常会估算算法的操作单元数量来代表程序消耗的时间,这里默认CPU的每个单元运行消耗的时间都是相同的。 @@ -80,13 +80,13 @@ O(2*n^2 + 10*n) O(n^2 + n) ``` -只保留保留最高项,去掉数量级小一级的n (因为n^2 的数据规模远大于n),最终简化为: +只保留最高项,去掉数量级小一级的n (因为n^2 的数据规模远大于n),最终简化为: ``` O(n^2) ``` -如果这一步理解有困难,那也可以做提取n的操作,变成O(n(n+1)),省略加法常数项后也就别变成了: +如果这一步理解有困难,那也可以做提取n的操作,变成O(n(n+1)),省略加法常数项后也就变成了: ``` O(n^2) @@ -96,7 +96,7 @@ O(n^2) 也可以用另一种简化的思路,其实当n大于40的时候, 这个复杂度会恒小于O(3 × n^2), -O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项系数最终时间复杂度也是O(n^2)。 +O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),3 × n^2省略掉常数项系数,最终时间复杂度也是O(n^2)。 ## O(log n)中的log是以什么为底? @@ -127,7 +127,7 @@ O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项 接下来再想一下其他解题思路。 -先排对n个字符串按字典序来排序,排序后n个字符串就是有序的,意味着两个相同的字符串就是挨在一起,然后在遍历一遍n个字符串,这样就找到两个相同的字符串了。 +先对n个字符串按字典序来排序,排序后n个字符串就是有序的,意味着两个相同的字符串就是挨在一起,然后再遍历一遍n个字符串,这样就找到两个相同的字符串了。 那看看这种算法的时间复杂度,快速排序时间复杂度为O(nlog n),依然要考虑字符串的长度是m,那么快速排序每次的比较都要有m次的字符比较的操作,就是O(m × n × log n)。 @@ -139,13 +139,13 @@ O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项 所以先把字符串集合排序再遍历一遍找到两个相同字符串的方法要比直接暴力枚举的方式更快。 -这就是我们通过分析两种算法的时间复杂度得来的。 +这就是我们通过分析两种算法的时间复杂度得来的结论。 **当然这不是这道题目的最优解,我仅仅是用这道题目来讲解一下时间复杂度**。 ## 总结 -本篇讲解了什么是时间复杂度,复杂度是用来干什么,以及数据规模对时间复杂度的影响。 +本篇讲解了什么是时间复杂度,复杂度是用来干什么的,以及数据规模对时间复杂度的影响。 还讲解了被大多数同学忽略的大O的定义以及log究竟是以谁为底的问题。 From df11fce6e858ba356eb0a5c8c400634f37188434 Mon Sep 17 00:00:00 2001 From: wangzilong Date: Fri, 29 Dec 2023 10:56:48 +0800 Subject: [PATCH 58/59] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200203.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0=20go=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=A2=9E=E5=8A=A0=E7=9B=B4=E6=8E=A5=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E5=8E=9F=E9=93=BE=E8=A1=A8=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 780f9c36..d6d7e6c2 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -330,7 +330,40 @@ class Solution: ``` ### Go: +直接使用原链表 +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeElements(head *ListNode, val int) *ListNode { + //依旧是先定义逻辑 + + //如果原链表的头节点为val的话,head=head.next,且为持续过程,防止头节点后面的节点也为Val + //这里前置循环 并且要判定head 是否为nil,防止出错 + for head != nil && head.Val == val {//由于leetcode代码运行方式,for循环条件判断前后顺序不能修改,下面的for循环也同样如此 + head = head.Next + } + cur := head + + for cur != nil && cur.Next != nil { + if cur.Next.Val == val { + cur.Next = cur.Next.Next + } else { + cur = cur.Next + } + } + + return head + +} + +``` +虚拟头节点方式: ```go /** * Definition for singly-linked list. From 71f51fcde4f28abedc24f46c923e9a47b21799b9 Mon Sep 17 00:00:00 2001 From: Chenxue3 <115330251+XueshanChen@users.noreply.github.com> Date: Fri, 29 Dec 2023 20:15:58 +1300 Subject: [PATCH 59/59] =?UTF-8?q?Update=20=E9=93=BE=E8=A1=A8=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=80.md=20=E6=B7=BB=E5=8A=A0C#=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/链表理论基础.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index 9dc45242..88e41d7d 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -250,9 +250,32 @@ typedef struct ListNodeT { } ListNode; ``` +### C# + +```c# +public class Node +{ + // 节点存储的数据 + public T Data { get; set; } + + // 指向下一个节点的引用 + public Node Next { get; set; } + + // 节点的构造函数,用于初始化节点 + public Node(T data) + { + Data = data; + Next = null; // 初始时没有下一个节点,因此设为 null + } +} +``` + + + + +

-