From b05f66d853a42afa17bb98963c2fdf65c3bcd6a8 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 4 Jan 2024 10:41:09 +0800 Subject: [PATCH 001/118] =?UTF-8?q?Update0406.=E6=A0=B9=E6=8D=AE=E5=AE=A1?= =?UTF-8?q?=E7=A8=BF=E9=87=8D=E5=BB=BA=E9=98=9F=E5=88=97=EF=BC=8C=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0406.根据身高重建队列.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index 9cd78fac..b0b02c14 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -396,6 +396,29 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int[][] ReconstructQueue(int[][] people) + { + Array.Sort(people, (a, b) => + { + if (a[0] == b[0]) + { + return a[1] - b[1]; + } + return b[0] - a[0]; + }); + var res = new List(); + for (int i = 0; i < people.Length; i++) + { + res.Insert(people[i][1], people[i]); + } + return res.ToArray(); + } +} +```

From 709b5babf0c01f4aa35034ab45f948531e15964e Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 4 Jan 2024 11:12:29 +0800 Subject: [PATCH 002/118] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DC#=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E9=AB=98=E4=BA=AE=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 4 ++-- problems/0017.电话号码的字母组合.md | 2 +- problems/0024.两两交换链表中的节点.md | 2 +- problems/0028.实现strStr.md | 2 +- problems/0034.在排序数组中查找元素的第一个和最后一个位置.md | 2 +- problems/0062.不同路径.md | 2 +- problems/0070.爬楼梯.md | 2 +- problems/0077.组合.md | 2 +- problems/0090.子集II.md | 2 +- problems/0098.验证二叉搜索树.md | 2 +- problems/0101.对称二叉树.md | 2 +- problems/0102.二叉树的层序遍历.md | 4 ++-- problems/0104.二叉树的最大深度.md | 6 +++--- problems/0106.从中序与后序遍历序列构造二叉树.md | 2 +- problems/0110.平衡二叉树.md | 2 +- problems/0111.二叉树的最小深度.md | 4 ++-- problems/0112.路径总和.md | 2 +- problems/0151.翻转字符串里的单词.md | 2 +- problems/0222.完全二叉树的节点个数.md | 2 +- problems/0235.二叉搜索树的最近公共祖先.md | 2 +- problems/0236.二叉树的最近公共祖先.md | 2 +- problems/0257.二叉树的所有路径.md | 2 +- problems/0404.左叶子之和.md | 2 +- problems/0450.删除二叉搜索树中的节点.md | 2 +- problems/0459.重复的子字符串.md | 2 +- problems/0501.二叉搜索树中的众数.md | 2 +- problems/0509.斐波那契数.md | 4 ++-- problems/0513.找树左下角的值.md | 2 +- problems/0530.二叉搜索树的最小绝对差.md | 2 +- problems/0538.把二叉搜索树转换为累加树.md | 2 +- problems/0617.合并二叉树.md | 2 +- problems/0654.最大二叉树.md | 2 +- problems/0669.修剪二叉搜索树.md | 2 +- problems/0700.二叉搜索树中的搜索.md | 2 +- problems/0707.设计链表.md | 2 +- problems/0746.使用最小花费爬楼梯.md | 2 +- problems/二叉树的统一迭代法.md | 6 +++--- problems/二叉树的迭代遍历.md | 2 +- problems/二叉树的递归遍历.md | 6 +++--- problems/面试题02.07.链表相交.md | 2 +- 40 files changed, 50 insertions(+), 50 deletions(-) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 614f6051..b13f9ac3 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -618,7 +618,7 @@ char * longestPalindrome(char * s){ ### C#: 動態規則: -```c# +```csharp public class Solution { public string LongestPalindrome(string s) { @@ -648,7 +648,7 @@ public class Solution { ``` 雙指針: -```C# +```csharp public class Solution { int maxlenth = 0; int left = 0; diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 8a16008a..cbd99f8d 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -733,7 +733,7 @@ def backtracking(result, letter_map, digits, path, index) end ``` ### C# -```C# +```csharp public class Solution { public IList res = new List(); diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 405f4183..b2a830a7 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -462,7 +462,7 @@ impl Solution { ``` ### C# -```C# +```csharp // 虚拟头结点 public ListNode SwapPairs(ListNode head) { diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index bf4ad600..25b81799 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1359,7 +1359,7 @@ impl Solution { ``` >前缀表统一不减一 -```C# +```csharp public int StrStr(string haystack, string needle) { if (string.IsNullOrEmpty(needle)) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index 3bf90e3b..22936fef 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -331,7 +331,7 @@ class Solution { ### C# -```c# +```csharp public int[] SearchRange(int[] nums, int target) { var leftBorder = GetLeftBorder(nums, target); diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index b7ce542e..5131fdbb 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -537,7 +537,7 @@ object Solution { ### c# -```c# +```csharp public class Solution { public int UniquePaths(int m, int n) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 7a59221d..d300683e 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -470,7 +470,7 @@ object Solution { ### C# -```c# +```csharp public class Solution { public int ClimbStairs(int n) { if(n<=2) return n; diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 8bca6f24..103fb627 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -793,7 +793,7 @@ end ``` ### C# -```C# +```csharp // 暴力 public class Solution { diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 9fc334a4..1bb63a34 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -641,7 +641,7 @@ object Solution { } ``` ### C# -```c# +```csharp public class Solution { public IList> res = new List>(); diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 319ad1aa..88e16282 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -792,7 +792,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public long val = Int64.MinValue; public bool IsValidBST(TreeNode root) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 1b777dd5..8442f0ab 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -898,7 +898,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public bool IsSymmetric(TreeNode root) { diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index e977279c..4411b560 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -463,7 +463,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public IList> LevelOrder(TreeNode root) { var res = new List>(); @@ -825,7 +825,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public IList> LevelOrderBottom(TreeNode root) { var res = new List>(); diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index b89dbf45..f4c6cfc8 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -1033,7 +1033,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归法 public int MaxDepth(TreeNode root) { if(root == null) return 0; @@ -1044,7 +1044,7 @@ public int MaxDepth(TreeNode root) { return 1 + Math.Max(leftDepth, rightDepth); } ``` -```C# +```csharp // 前序遍历 int result = 0; public int MaxDepth(TreeNode root) @@ -1065,7 +1065,7 @@ public void GetDepth(TreeNode root, int depth) return; } ``` -```C# +```csharp // 迭代法 public int MaxDepth(TreeNode root) { diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index dc517480..0e0ab1d7 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -1229,7 +1229,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public TreeNode BuildTree(int[] inorder, int[] postorder) { if (inorder.Length == 0 || postorder.Length == null) return null; diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 41669bff..40fdcd14 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -909,7 +909,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public bool IsBalanced(TreeNode root) { return GetHeight(root) == -1 ? false : true; diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 46523349..6d1632d5 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -709,7 +709,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public int MinDepth(TreeNode root) { @@ -725,7 +725,7 @@ public int MinDepth(TreeNode root) return res; } ``` -```C# +```csharp // 迭代 public int MinDepth(TreeNode root) { diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index f1ce7637..28134a7c 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1513,7 +1513,7 @@ impl Solution { ``` ### C# -```C# +```csharp // 0112.路径总和 // 递归 public bool HasPathSum(TreeNode root, int targetSum) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d15bb5f3..520f17a7 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -973,7 +973,7 @@ char * reverseWords(char * s){ ``` ### C# -```C# LINQ高级方法 +```csharp LINQ高级方法 public string ReverseWords(string s) { return string.Join(' ', s.Trim().Split(' ',StringSplitOptions.RemoveEmptyEntries).Reverse()); } diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index ef6e88aa..d93d2a33 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -868,7 +868,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public int CountNodes(TreeNode root) { diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b27a231e..cec8a1dd 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -514,7 +514,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 0e99f1c2..049f70c7 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -432,7 +432,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 9ba165c7..4c6c92c5 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -901,7 +901,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public IList BinaryTreePaths(TreeNode root) { List path = new(); diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 6dfcc886..3d0f5a8a 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -652,7 +652,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public int SumOfLeftLeaves(TreeNode root) { diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 13c25023..8922a14e 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -772,7 +772,7 @@ impl Solution { ### C# > 递归法: -```C# +```csharp public TreeNode DeleteNode(TreeNode root, int key) { // 第一种情况:没找到删除的节点,遍历到空节点直接返回了 if (root == null) return null; diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 3245d948..311e3a69 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -682,7 +682,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 前缀表不减一 public bool RepeatedSubstringPattern(string s) { diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 5b26d580..20627d1a 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -1010,7 +1010,7 @@ pub fn find_mode(root: Option>>) -> Vec { } ``` ### C# -```C# +```csharp // 递归 public class Solution { diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 0c073db5..71c022bd 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -439,7 +439,7 @@ object Solution { 动态规划: -```c# +```csharp public class Solution { public int Fib(int n) @@ -459,7 +459,7 @@ public class Solution 递归: -```c# +```csharp public class Solution { public int Fib(int n) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 0e2f4266..3cdcc801 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -685,7 +685,7 @@ impl Solution { } ``` ### C# -```C# +```csharp //递归 int maxDepth = -1; int res = 0; diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index f08df577..82b3f5d4 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -648,7 +648,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public class Solution { diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 07cae1ad..7fcb5efd 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -530,7 +530,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public class Solution { diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index 9efeb56d..3478a2af 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -789,7 +789,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public TreeNode MergeTrees(TreeNode root1, TreeNode root2) { if (root1 == null) return root2; diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 6b343840..f54558a6 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -583,7 +583,7 @@ impl Solution { } ``` ### C# -```C# +```csharp public TreeNode ConstructMaximumBinaryTree(int[] nums) { if (nums.Length == 0) return null; diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 229a2ab1..916013c5 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -568,7 +568,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public TreeNode TrimBST(TreeNode root, int low, int high) { diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 65e69219..9efb1e05 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -465,7 +465,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 递归 public TreeNode SearchBST(TreeNode root, int val) { diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index a08227d9..fecdbc3c 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -1486,7 +1486,7 @@ impl MyLinkedList { ``` ### C# -```C# +```csharp class ListNode { public int val; diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 6fb518c3..d13ff19f 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -500,7 +500,7 @@ object Solution { ### C# -```c# +```csharp public class Solution { public int MinCostClimbingStairs(int[] cost) diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index ad79424d..ee4899b1 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -742,7 +742,7 @@ impl Solution{ } ``` ### C# -```C# +```csharp // 前序遍历 public IList PreorderTraversal(TreeNode root) { @@ -772,7 +772,7 @@ public IList PreorderTraversal(TreeNode root) return res; } ``` -```C# +```csharp // 中序遍历 public IList InorderTraversal(TreeNode root) { @@ -803,7 +803,7 @@ public IList InorderTraversal(TreeNode root) } ``` -```C# +```csharp // 后序遍历 public IList PostorderTraversal(TreeNode root) { diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index e39709b8..35a01a7f 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -696,7 +696,7 @@ impl Solution { } ``` ### C# -```C# +```csharp // 前序遍历 public IList PreorderTraversal(TreeNode root) { diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 6dad6e56..92a8341f 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -566,7 +566,7 @@ impl Solution { ``` ### C# -```C# +```csharp // 前序遍历 public IList PreorderTraversal(TreeNode root) { @@ -584,7 +584,7 @@ public void Traversal(TreeNode cur, IList res) Traversal(cur.right, res); } ``` -```C# +```csharp // 中序遍历 public IList InorderTraversal(TreeNode root) { @@ -601,7 +601,7 @@ public void Traversal(TreeNode cur, IList res) Traversal(cur.right, res); } ``` -```C# +```csharp // 后序遍历 public IList PostorderTraversal(TreeNode root) { diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index adeaa413..d0967b8b 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -503,7 +503,7 @@ object Solution { } ``` ### C# -```C# +```csharp public ListNode GetIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; From 55d676e194180cb33564a7b3019068ccd1ad834f Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 5 Jan 2024 14:08:10 +0800 Subject: [PATCH 003/118] =?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=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/0452.用最少数量的箭引爆气球.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index 90cd7085..cd57f83b 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -332,6 +332,24 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int FindMinArrowShots(int[][] points) + { + if (points.Length == 0) return 0; + Array.Sort(points, (a, b) => a[0].CompareTo(b[0])); + int count = 1; + for (int i = 1; i < points.Length; i++) + { + if (points[i][0] > points[i - 1][1]) count++; + else points[i][1] = Math.Min(points[i][1], points[i - 1][1]); + } + return count; + } +} +```

From 6add8c3287ade5bbfefd6d7042863376cff1ca39 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 6 Jan 2024 09:33:13 +0800 Subject: [PATCH 004/118] =?UTF-8?q?Update=200435.=E6=97=A0=E9=87=8D?= =?UTF-8?q?=E5=8F=A0=E5=8C=BA=E9=97=B4=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/0435.无重叠区间.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index c307532e..1a33f98e 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -441,6 +441,27 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int EraseOverlapIntervals(int[][] intervals) + { + if (intervals.Length == 0) return 0; + Array.Sort(intervals, (a, b) => a[1].CompareTo(b[1])); + int res = 1, end = intervals[0][1]; + for (int i = 1; i < intervals.Length; i++) + { + if (end <= intervals[i][0]) + { + end = intervals[i][1]; + res++; + } + } + return intervals.Length - res; + } +} +```

From 30af534ee95204e51da960ba3787bfa3b90d14b9 Mon Sep 17 00:00:00 2001 From: dengyongchi Date: Sat, 6 Jan 2024 10:56:02 +0800 Subject: [PATCH 005/118] =?UTF-8?q?feat:=20=E5=85=B3=E4=BA=8E=E5=9B=BE?= =?UTF-8?q?=E7=AC=AC1971=E9=A2=98js=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1971.寻找图中是否存在路径.md | 121 +++++++++++++++++++++----- 1 file changed, 99 insertions(+), 22 deletions(-) diff --git a/problems/1971.寻找图中是否存在路径.md b/problems/1971.寻找图中是否存在路径.md index 27ee9147..132b0181 100644 --- a/problems/1971.寻找图中是否存在路径.md +++ b/problems/1971.寻找图中是否存在路径.md @@ -4,30 +4,28 @@

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

-# 1971. 寻找图中是否存在路径 +# 1971. 寻找图中是否存在路径 [题目链接](https://leetcode.cn/problems/find-if-path-exists-in-graph/) -有一个具有 n个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。 +有一个具有 n 个顶点的 双向 图,其中每个顶点标记从 0 到 n - 1(包含 0 和 n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。 请你确定是否存在从顶点 start 开始,到顶点 end 结束的 有效路径 。 -给你数组 edges 和整数 n、start和end,如果从 start 到 end 存在 有效路径 ,则返回 true,否则返回 false 。 - - -![](https://code-thinking-1253855093.file.myqcloud.com/pics/20220705101442.png) +给你数组 edges 和整数 n、start 和 end,如果从 start 到 end 存在 有效路径 ,则返回 true,否则返回 false 。 +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20220705101442.png) 提示: -* 1 <= n <= 2 * 10^5 -* 0 <= edges.length <= 2 * 10^5 -* edges[i].length == 2 -* 0 <= ui, vi <= n - 1 -* ui != vi -* 0 <= start, end <= n - 1 -* 不存在双向边 -* 不存在指向顶点自身的边 +- 1 <= n <= 2 \* 10^5 +- 0 <= edges.length <= 2 \* 10^5 +- edges[i].length == 2 +- 0 <= ui, vi <= n - 1 +- ui != vi +- 0 <= start, end <= n - 1 +- 不存在双向边 +- 不存在指向顶点自身的边 ## 思路 @@ -70,7 +68,7 @@ void join(int u, int v) { } ``` -以上模板中,只要修改 n 大小就可以,本题n不会超过2 * 10^5。 +以上模板中,只要修改 n 大小就可以,本题 n 不会超过 2 \* 10^5。 并查集主要有三个功能。 @@ -80,17 +78,17 @@ void join(int u, int v) { 简单介绍并查集之后,我们再来看一下这道题目。 -为什么说这道题目是并查集基础题目,题目中各个点是双向图链接,那么判断 一个顶点到另一个顶点有没有有效路径其实就是看这两个顶点是否在同一个集合里。 +为什么说这道题目是并查集基础题目,题目中各个点是双向图链接,那么判断 一个顶点到另一个顶点有没有有效路径其实就是看这两个顶点是否在同一个集合里。 -如何算是同一个集合呢,有边连在一起,就算是一个集合。 +如何算是同一个集合呢,有边连在一起,就算是一个集合。 -此时我们就可以直接套用并查集模板。 +此时我们就可以直接套用并查集模板。 -使用join(int u, int v)将每条边加入到并查集。 +使用 join(int u, int v)将每条边加入到并查集。 -最后 isSame(int u, int v) 判断是否是同一个根 就可以了。 +最后 isSame(int u, int v) 判断是否是同一个根 就可以了。 -C++代码如下: +C++代码如下: ```CPP class Solution { @@ -191,7 +189,7 @@ class Solution { ### Python: -PYTHON并查集解法如下: +PYTHON 并查集解法如下: ```PYTHON class Solution: @@ -206,6 +204,85 @@ class Solution: return find(source) == find(destination) ``` +### Javascript: + +Javascript 并查集解法如下: + +```Javascript +class unionF{ + constructor(n){ + this.count = n + this.roots = new Array(n).fill(0).map((item,index)=>index) + } + + findRoot(x){ + if(this.roots[x]!==x){ + this.roots[x] = this.findRoot(this.roots[x]) + } + return this.roots[x] + } + + union(x,y){ + const rx = this.findRoot(x) + const ry = this.findRoot(y) + this.roots[rx] = ry + this.count-- + } + + isConnected(x,y){ + return this.findRoot(x)===this.findRoot(y) + } +} + +var validPath = function(n, edges, source, destination) { + const UF = new unionF(n) + for(const [s,t] of edges){ + UF.union(s,t) + } + return UF.isConnected(source,destination) +}; +``` + +Javascript 双向 bfs 解法如下: + +```Javascript +var validPath = function(n, edges, source, destination) { + const graph = new Array(n).fill(0).map(()=>[]) + for(const [s,t] of edges){ + graph[s].push(t) + graph[t].push(s) + } + + const visited = new Array(n).fill(false) + function bfs(start,end,graph){ + const startq = [start] + const endq = [end] + while(startq.length&&endq.length){ + const slen = startq.length + for(let i = 0;i From 39f25c499818ef9da78a1c09264738e68292b96f Mon Sep 17 00:00:00 2001 From: CUI Date: Sat, 6 Jan 2024 15:01:08 +0800 Subject: [PATCH 006/118] =?UTF-8?q?=E6=B7=BB=E5=8A=A0go=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E8=B4=AA=E5=BF=83=E4=BC=98=E5=8C=96=E7=89=88=E6=9C=AC=E5=9C=A8?= =?UTF-8?q?0045.=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8FII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index e006caa2..d290f55e 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -285,6 +285,34 @@ class Solution: ### Go + +```go +/** + * @date: 2024 Jan 06 + * @time: 13:44 + * @author: Chris +**/ +// 贪心算法优化版 + +// 记录步骤规则:每超过上一次可达最大范围,需要跳跃一次,次数+1 +// 记录位置:i == lastDistance + 1 +func jump(nums []int) int { + // 根据题目规则,初始位置为nums[0] + lastDistance := 0 // 上一次覆盖范围 + curDistance := 0 // 当前覆盖范围(可达最大范围) + minStep := 0 // 记录最少跳跃次数 + + for i := 0; i < len(nums); i++ { + if i == lastDistance+1 { // 在上一次可达范围+1的位置,记录步骤 + minStep++ // 跳跃次数+1 + lastDistance = curDistance // 记录时才可以更新 + } + curDistance = max(nums[i]+i, curDistance) // 更新当前可达的最大范围 + } + return minStep +} +``` + ```go // 贪心版本一 func jump(nums []int) int { From 93ab9befe85fdd3056765b3414b8b442a7f2258d Mon Sep 17 00:00:00 2001 From: Chenxue3 <115330251+XueshanChen@users.noreply.github.com> Date: Sat, 6 Jan 2024 23:51:02 +1300 Subject: [PATCH 007/118] =?UTF-8?q?Update=200225.=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md=20=E5=A2=9E=E5=8A=A0C#?= =?UTF-8?q?=E5=8D=95=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index d89bf44b..6900e668 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -1046,6 +1046,8 @@ class MyStack() { ### C#: +> 双队列 + ```csharp public class MyStack { Queue queue1; @@ -1080,6 +1082,54 @@ public class MyStack { } ``` +> 单队列 + +```c# +/* + * @lc app=leetcode id=225 lang=csharp + * 版本二:单队列 + * [225] Implement Stack using Queues + */ + +// @lc code=start +public class MyStack { + Queue myQueue; + public MyStack() { + myQueue = new Queue(); + } + + public void Push(int x) { + myQueue.Enqueue(x); + } + + //使用一个队列实现 + public int Pop() { + //一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。 + for (var i = 0; i < myQueue.Count-1; i++) + { + myQueue.Enqueue(myQueue.Dequeue()); + } + return myQueue.Dequeue(); + } + + //复用Pop()的代码 + public int Top() { + int res = Pop(); + myQueue.Enqueue(res); + return res; + } + + public bool Empty() { + return (myQueue.Count == 0); + } +} + +// @lc code=end + +``` + + + ### PHP: > 双队列 @@ -1203,3 +1253,4 @@ impl MyStack { + From e4db0542d4d8703df031e9e6a158a02a3467b219 Mon Sep 17 00:00:00 2001 From: nuo Date: Sun, 7 Jan 2024 05:07:06 +0800 Subject: [PATCH 008/118] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=9A=E5=8E=9F?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=BD=BF=E7=94=A8=E4=BA=86=E9=9D=9E=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E6=9C=9F=E5=B8=B8=E9=87=8F=E5=A3=B0=E6=98=8E=E6=95=B0?= =?UTF-8?q?=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现将int next[needle.size()];替换为vector next(needle.size()); --- problems/0028.实现strStr.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index bf4ad600..27ef761c 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -425,8 +425,8 @@ public: if (needle.size() == 0) { return 0; } - int next[needle.size()]; - getNext(next, needle); + vector next(needle.size()); + getNext(&next[0], needle); int j = -1; // // 因为next数组里记录的起始位置为-1 for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始 while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配 @@ -524,8 +524,8 @@ public: if (needle.size() == 0) { return 0; } - int next[needle.size()]; - getNext(next, needle); + vector next(needle.size()); + getNext(&next[0], needle); int j = 0; for (int i = 0; i < haystack.size(); i++) { while(j > 0 && haystack[i] != needle[j]) { @@ -1428,4 +1428,3 @@ public int[] GetNext(string needle) - From 20f331f9043725ad9c39d27bf9912c441b6bcf48 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 7 Jan 2024 10:04:45 +0800 Subject: [PATCH 009/118] =?UTF-8?q?Update=200763.=E5=88=92=E5=88=86?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E5=8C=BA=E9=97=B4=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/0763.划分字母区间.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md index 41314456..4e9ec578 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -404,6 +404,32 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public IList PartitionLabels(string s) + { + int[] location = new int[27]; + for (int i = 0; i < s.Length; i++) + { + location[s[i] - 'a'] = i; + } + List res = new List(); + int left = 0, right = 0; + for (int i = 0; i < s.Length; i++) + { + right = Math.Max(right, location[s[i] - 'a']); + if (i == right) + { + res.Add(right - left + 1); + left = i + 1; + } + } + return res; + } +} +```

From 98827c14d0efdceaeb6ebed14f82c4c196e01f5c Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 8 Jan 2024 10:10:12 +0800 Subject: [PATCH 010/118] =?UTF-8?q?Update=200056.=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=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/0056.合并区间.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index 95781b1a..122e783a 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -336,6 +336,32 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int[][] Merge(int[][] intervals) + { + if (intervals.Length == 0) + return intervals; + Array.Sort(intervals, (a, b) => a[0] - b[0]); + List> res = new List>(); + res.Add(intervals[0].ToList()); + for (int i = 1; i < intervals.Length; i++) + { + if (res[res.Count - 1][1] >= intervals[i][0]) + { + res[res.Count - 1][1] = Math.Max(res[res.Count - 1][1], intervals[i][1]); + } + else + { + res.Add(intervals[i].ToList()); + } + } + return res.Select(x => x.ToArray()).ToArray(); + } +} +```

From 6b38053a63c0a1896ac6ec7905fc17a0a770f91b Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 9 Jan 2024 10:47:42 +0800 Subject: [PATCH 011/118] =?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=EF=BC=8C=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0C#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0738.单调递增的数字.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index c2215cf6..400dc90d 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -392,6 +392,30 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int MonotoneIncreasingDigits(int n) + { + char[] s = n.ToString().ToCharArray(); + int flag = s.Length; + for (int i = s.Length - 1; i > 0; i--) + { + if (s[i - 1] > s[i]) + { + flag = i; + s[i - 1]--; + } + } + for (int i = flag; i < s.Length; i++) + { + s[i] = '9'; + } + return int.Parse(new string(s)); + } +} +```

From f292cbaf2ed861021db70f6b4c2aba7d028f2d64 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 10 Jan 2024 10:02:48 +0800 Subject: [PATCH 012/118] =?UTF-8?q?Update=200968.=E7=9B=91=E6=8E=A7?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=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/0968.监控二叉树.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index be04bd47..305f3ae5 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -726,6 +726,31 @@ impl Solution { } } +``` +### C# +```csharp +public class Solution +{ + public int res = 0; + public int MinCameraCover(TreeNode root) + { + if (Traversal(root) == 0) res++; + return res; + } + public int Traversal(TreeNode cur) + { + if (cur == null) return 2; + int left = Traversal(cur.left); + int right = Traversal(cur.right); + if (left == 2 && right == 2) return 0; + else if (left == 0 || right == 0) + { + res++; + return 1; + } + else return 2; + } +} ```

From 650e33bc709f59df007625ff524906c4bd59585c Mon Sep 17 00:00:00 2001 From: Chenxue3 <115330251+XueshanChen@users.noreply.github.com> Date: Thu, 11 Jan 2024 14:50:59 +1300 Subject: [PATCH 013/118] =?UTF-8?q?update=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md=20=E5=A2=9E=E5=8A=A0C#?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index e2c6d83c..50d592a2 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -302,9 +302,19 @@ impl TreeNode { } } } -``` +``` +```c# +public class TreeNode +{ + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int x) { val = x; } +} +```

+ From f6557d7ddc15aff15dfe4b5dcc956aca98e7324c Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 15:31:33 +0800 Subject: [PATCH 014/118] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E6=95=B0=E9=87=8F.=E6=B7=B1=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 | 67 ++++++++++++++------------------ 1 file changed, 29 insertions(+), 38 deletions(-) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index a4b93c3d..7431fbef 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -389,50 +389,41 @@ function numIslands(grid: string[][]): number { ### Go ```go + +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + func numIslands(grid [][]byte) int { - // 用1标记已访问 - visited := make([][]int, len(grid)) - for i := 0; i < len(visited); i++{ - visited[i] = make([]int, len(grid[0])) - } + res := 0 - var bfs func(x, y int) - bfs = func(x, y int){ - stack := make([][]int, 0) - stack = append(stack, []int{x, y}) - moveX := []int{1, -1, 0, 0} - moveY := []int{0, 0, 1, -1} + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } - for len(stack) != 0{ - node := stack[len(stack) - 1] - stack = stack[:len(stack) - 1] + for i, rows := range grid { + for j, v := range rows { + if v == '1' && !visited[i][j] { + res++ + dfs(grid, visited, i, j) + } + } + } - for i := 0; i < 4; i++{ - dx := moveX[i] + node[0] - dy := moveY[i] + node[1] - if dx < 0 || dx >= len(grid) || dy < 0 || dy >= len(grid[0]) || visited[dx][dy] == 1{ - continue - } - visited[dx][dy] = 1 - if grid[dx][dy] == '1'{ - stack = append(stack, []int{dx,dy}) - } - } - } - } + return res +} - result := 0 - for i := 0; i < len(grid); i++{ - for j := 0; j < len(grid[0]); j++{ - if visited[i][j] == 0 && grid[i][j] == '1'{ - bfs(i, j) - visited[i][j] = 1 - result++ - } - } - } +func dfs(grid [][]byte, visited [][]bool, i, j int) { + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == '1' && !visited[x][y] { + visited[x][y] = true + dfs(grid, visited, x, y) + } + } - return result } ``` From 0dc7f2f76565da3796830987274f7e8c7e2e4002 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 16:56:54 +0800 Subject: [PATCH 015/118] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E6=95=B0=E9=87=8F.=E5=B9=BF=E6=90=9C=E7=89=88.md=20for=20golan?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0200.岛屿数量.广搜版.md | 45 +++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index a7dd117b..5c77ed05 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -321,11 +321,54 @@ function numIslands2(grid: string[][]): number { } ``` +### Go + +```go + +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + +func numIslands(grid [][]byte) int { + res := 0 + + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } + + for i, rows := range grid { + for j, v := range rows { + if v == '1' && !visited[i][j] { + res++ + bfs(grid, visited, i, j) + } + } + } + return res +} + +func bfs(grid [][]byte, visited [][]bool, i, j int) { + queue := [][2]int{{i, j}} + visited[i][j] = true // 标记已访问,循环中标记会导致重复 + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == '1' && !visited[x][y] { + visited[x][y] = true + queue = append(queue, [2]int{x, y}) + } + } + } +} +``` ### Rust ```rust - use std::collections::VecDeque; impl Solution { const DIRECTIONS: [(i32, i32); 4] = [(0, 1), (1, 0), (-1, 0), (0, -1)]; From 26fc4c41720aee859956309caa97bd6434120840 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 16:58:01 +0800 Subject: [PATCH 016/118] =?UTF-8?q?Update=200200.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E6=95=B0=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 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.广搜版.md b/problems/0200.岛屿数量.广搜版.md index 5c77ed05..85471f73 100644 --- a/problems/0200.岛屿数量.广搜版.md +++ b/problems/0200.岛屿数量.广搜版.md @@ -199,7 +199,9 @@ class Solution { ### Python + BFS solution + ```python class Solution: def __init__(self): @@ -240,6 +242,7 @@ class Solution: ``` ### JavaScript + ```javascript var numIslands = function (grid) { let dir = [[0, 1], [1, 0], [-1, 0], [0, -1]]; // 四个方向 @@ -324,7 +327,6 @@ function numIslands2(grid: string[][]): number { ### Go ```go - var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} func numIslands(grid [][]byte) int { From 26c4004d74c2480a96722a563a5dd724cedb1e71 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 17:40:16 +0800 Subject: [PATCH 017/118] Apply suggestions from code review --- problems/0200.岛屿数量.深搜版.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index 7431fbef..18442943 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -413,13 +413,13 @@ func numIslands(grid [][]byte) int { } func dfs(grid [][]byte, visited [][]bool, i, j int) { + visited[x][y] = true for _, d := range DIRECTIONS { x, y := i+d[0], j+d[1] if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { continue } if grid[x][y] == '1' && !visited[x][y] { - visited[x][y] = true dfs(grid, visited, x, y) } } From a0790023246d80328b377517a1d83b7580fa7dc7 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 18:00:20 +0800 Subject: [PATCH 018/118] =?UTF-8?q?Update=200695.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E9=9D=A2=E7=A7=AF.md=20for=20go?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0695.岛屿的最大面积.md | 144 ++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) diff --git a/problems/0695.岛屿的最大面积.md b/problems/0695.岛屿的最大面积.md index 74470ae5..a87acb82 100644 --- a/problems/0695.岛屿的最大面积.md +++ b/problems/0695.岛屿的最大面积.md @@ -428,6 +428,150 @@ var maxAreaOfIsland = function (grid) { }; ``` +### Go + +dsf: 版本一 + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func maxAreaOfIsland(grid [][]int) int { + res := 0 + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } + + for i, rows := range grid { + for j, v := range rows { + if v == 1 && !visited[i][j] { + // 第一种写法,重制 count,必定有 1 个 + count = 1 + dfs(grid, visited, i, j) + res = max(res, count) + } + + } + } + + return res +} + +// 第一种写法 +func dfs(grid [][]int, visited [][]bool, i, j int) { + visited[i][j] = true // 标记已访问,循环中未标记会导致重复 + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == 1 && !visited[x][y] { + count++ + dfs(grid, visited, x, y) + } + } +} +``` + +dfs:版本二 + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func maxAreaOfIsland(grid [][]int) int { + res := 0 + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } + + for i, rows := range grid { + for j, v := range rows { + if v == 1 && !visited[i][j] { + // 第二种写法 + count = 0 + dfs(grid, visited, i, j) + res = max(res, count) + } + + } + } + + return res +} + +// 第二种写法 +func dfs(grid [][]int, visited [][]bool, i, j int) { + if visited[i][j] || grid[i][j] == 0 { + return + } + visited[i][j] = true + count++ + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + dfs(grid, visited, x, y) + } +} +``` + +bfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func maxAreaOfIsland(grid [][]int) int { + res := 0 + visited := make([][]bool, len(grid)) + for i := 0; i < len(grid); i++ { + visited[i] = make([]bool, len(grid[0])) + } + + for i, rows := range grid { + for j, v := range rows { + if v == 1 && !visited[i][j] { + // 第一种写法,重制 count,必定有 1 个 + // count = 1 + // 第二种写法以及 bfs + count = 0 + // dfs(grid, visited, i, j) + bfs(grid, visited, i, j) + res = max(res, count) + } + + } + } + + return res +} + +// bfs +func bfs(grid [][]int, visited [][]bool, i, j int) { + visited[i][j] = true + count++ + queue := [][2]int{{i, j}} + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == 1 && !visited[x][y] { + count++ + queue = append(queue, [2]int{x, y}) + visited[x][y] = true + } + } + } +} +``` ### Rust From 909971eb8b9bb5befb1c6ef25b08b754d09b3435 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Thu, 11 Jan 2024 18:01:34 +0800 Subject: [PATCH 019/118] =?UTF-8?q?Update=200695.=E5=B2=9B=E5=B1=BF?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E5=A4=A7=E9=9D=A2=E7=A7=AF.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0695.岛屿的最大面积.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/problems/0695.岛屿的最大面积.md b/problems/0695.岛屿的最大面积.md index a87acb82..87b1b5bb 100644 --- a/problems/0695.岛屿的最大面积.md +++ b/problems/0695.岛屿的最大面积.md @@ -535,11 +535,7 @@ func maxAreaOfIsland(grid [][]int) int { for i, rows := range grid { for j, v := range rows { if v == 1 && !visited[i][j] { - // 第一种写法,重制 count,必定有 1 个 - // count = 1 - // 第二种写法以及 bfs count = 0 - // dfs(grid, visited, i, j) bfs(grid, visited, i, j) res = max(res, count) } From b13487089cb782412c156836be0dc00fef53d1da Mon Sep 17 00:00:00 2001 From: Chenxue3 <115330251+XueshanChen@users.noreply.github.com> Date: Thu, 11 Jan 2024 23:41:09 +1300 Subject: [PATCH 020/118] =?UTF-8?q?update=200116.=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87=E9=92=88?= =?UTF-8?q?.md=20=E5=A2=9E=E5=8A=A0C#=E8=BF=AD=E4=BB=A3=E5=92=8C=E9=80=92?= =?UTF-8?q?=E5=BD=92=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0116.填充每个节点的下一个右侧节点指针.md | 77 +++++++++++++++++++ problems/二叉树的递归遍历.md | 1 + 2 files changed, 78 insertions(+) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index 003ef75a..60ea9210 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -358,7 +358,84 @@ function connect(root: NodePro | null): NodePro | null { }; ``` +```csharp +//递归 +public class Solution { + public Node Connect(Node root) { + if (root == null) { + return null; + } + + ConnectNodes(root.left, root.right); + + return root; + } + private void ConnectNodes(Node node1, Node node2) { + if (node1 == null || node2 == null) { + return; + } + + // 将左子节点的 next 指向右子节点 + node1.next = node2; + + // 递归连接当前节点的左右子节点 + ConnectNodes(node1.left, node1.right); + ConnectNodes(node2.left, node2.right); + + // 连接跨越父节点的两个子树 + ConnectNodes(node1.right, node2.left); + } +} + + +// 迭代 +public class Solution +{ + public Node Connect(Node root) + { + Queue que = new Queue(); + + if (root != null) + { + que.Enqueue(root); + } + + while (que.Count > 0) + { + + var queSize = que.Count; + for (int i = 0; i < queSize; i++) + { + var cur = que.Dequeue(); + + // 当这个节点不是这一层的最后的节点 + if (i != queSize - 1) + { + // 当前节点指向下一个节点 + cur.next = que.Peek(); + } + // 否则指向空 + else + { + cur.next = null; + } + + if (cur.left != null) + { + que.Enqueue(cur.left); + } + if (cur.right != null) + { + que.Enqueue(cur.right); + } + } + } + + return root; + } +} +```

diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 6dad6e56..b6dd7b6f 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -623,3 +623,4 @@ public void Traversal(TreeNode cur, IList res) + From e36c15a01cf93e4ea2d30545c485f6c6969650aa Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Thu, 11 Jan 2024 21:43:31 +0800 Subject: [PATCH 021/118] =?UTF-8?q?Update=20kama54.=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=E6=95=B0=E5=AD=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama54.替换数字.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/problems/kama54.替换数字.md b/problems/kama54.替换数字.md index 2b3d53de..f5e30a70 100644 --- a/problems/kama54.替换数字.md +++ b/problems/kama54.替换数字.md @@ -56,36 +56,36 @@ C++代码如下: ```CPP -#include +#include using namespace std; int main() { string s; while (cin >> s) { + int sOldIndex = s.size() - 1; int count = 0; // 统计数字的个数 - int sOldSize = s.size(); for (int i = 0; i < s.size(); i++) { if (s[i] >= '0' && s[i] <= '9') { count++; } } - // 扩充字符串s的大小,也就是每个空格替换成"number"之后的大小 + // 扩充字符串s的大小,也就是将每个数字替换成"number"之后的大小 s.resize(s.size() + count * 5); - int sNewSize = s.size(); - // 从后先前将空格替换为"number" - for (int i = sNewSize - 1, j = sOldSize - 1; j < i; i--, j--) { - if (s[j] > '9' || s[j] < '0') { - s[i] = s[j]; + int sNewIndex = s.size() - 1; + // 从后往前将数字替换为"number" + while (sOldIndex >= 0) { + if (s[sOldIndex] >= '0' && s[sOldIndex] <= '9') { + s[sNewIndex--] = 'r'; + s[sNewIndex--] = 'e'; + s[sNewIndex--] = 'b'; + s[sNewIndex--] = 'm'; + s[sNewIndex--] = 'u'; + s[sNewIndex--] = 'n'; } else { - s[i] = 'r'; - s[i - 1] = 'e'; - s[i - 2] = 'b'; - s[i - 3] = 'm'; - s[i - 4] = 'u'; - s[i - 5] = 'n'; - i -= 5; + s[sNewIndex--] = s[sOldIndex]; } + sOldIndex--; } - cout << s << endl; + cout << s << endl; } } From 49690a1712142e0739797b34c7422b155b6ae4e5 Mon Sep 17 00:00:00 2001 From: WmW Date: Fri, 12 Jan 2024 16:43:39 +0800 Subject: [PATCH 022/118] =?UTF-8?q?update=20455.=E5=88=86=E5=8F=91?= =?UTF-8?q?=E9=A5=BC=E5=B9=B2;=20=E4=BB=A3=E7=A0=81=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 778adc94..da4fd392 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -73,9 +73,9 @@ public: } }; ``` -* 时间复杂度:O(nlogn) -* 空间复杂度:O(1) +- 时间复杂度:O(nlogn) +- 空间复杂度:O(1) 从代码中可以看出我用了一个 index 来控制饼干数组的遍历,遍历饼干并没有再起一个 for 循环,而是采用自减的方式,这也是常用的技巧。 @@ -119,9 +119,9 @@ public: } }; ``` -* 时间复杂度:O(nlogn) -* 空间复杂度:O(1) +- 时间复杂度:O(nlogn) +- 空间复杂度:O(1) 细心的录友可以发现,这种写法,两个循环的顺序改变了,先遍历的饼干,在遍历的胃口,这是因为遍历顺序变了,我们是从小到大遍历。 @@ -177,7 +177,9 @@ class Solution { ``` ### Python + 贪心 大饼干优先 + ```python class Solution: def findContentChildren(self, g, s): @@ -192,7 +194,9 @@ class Solution: return result ``` + 贪心 小饼干优先 + ```python class Solution: def findContentChildren(self, g, s): @@ -229,7 +233,7 @@ func findContentChildren(g []int, s []int) int { ### Rust ```rust -pub fn find_content_children(mut children: Vec, mut cookie: Vec) -> i32 { +pub fn find_content_children(mut children: Vec, mut cookies: Vec) -> i32 { children.sort(); cookies.sort(); @@ -378,7 +382,9 @@ object Solution { } } ``` + ### C# + ```csharp public class Solution { From f25f062407a045d083e40d3174c8dc156636eb79 Mon Sep 17 00:00:00 2001 From: WmW Date: Fri, 12 Jan 2024 16:45:27 +0800 Subject: [PATCH 023/118] =?UTF-8?q?update=20455.=E5=88=86=E5=8F=91?= =?UTF-8?q?=E9=A5=BC=E5=B9=B2;=20=E4=BB=A3=E7=A0=81=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index da4fd392..6ae206db 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -73,9 +73,9 @@ public: } }; ``` +* 时间复杂度:O(nlogn) +* 空间复杂度:O(1) -- 时间复杂度:O(nlogn) -- 空间复杂度:O(1) 从代码中可以看出我用了一个 index 来控制饼干数组的遍历,遍历饼干并没有再起一个 for 循环,而是采用自减的方式,这也是常用的技巧。 @@ -119,9 +119,9 @@ public: } }; ``` +* 时间复杂度:O(nlogn) +* 空间复杂度:O(1) -- 时间复杂度:O(nlogn) -- 空间复杂度:O(1) 细心的录友可以发现,这种写法,两个循环的顺序改变了,先遍历的饼干,在遍历的胃口,这是因为遍历顺序变了,我们是从小到大遍历。 @@ -177,9 +177,7 @@ class Solution { ``` ### Python - 贪心 大饼干优先 - ```python class Solution: def findContentChildren(self, g, s): @@ -194,9 +192,7 @@ class Solution: return result ``` - 贪心 小饼干优先 - ```python class Solution: def findContentChildren(self, g, s): @@ -382,9 +378,7 @@ object Solution { } } ``` - ### C# - ```csharp public class Solution { From 29eb6f680f73bcee4d7039864be8bf1d58179adf Mon Sep 17 00:00:00 2001 From: Chenxue3 <115330251+XueshanChen@users.noreply.github.com> Date: Fri, 12 Jan 2024 21:45:48 +1300 Subject: [PATCH 024/118] =?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:=20Ad?= =?UTF-8?q?d=20559.n=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6=20C#=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 72 +++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index f4c6cfc8..1f55f197 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -1033,6 +1033,9 @@ impl Solution { } ``` ### C# + +0104.二叉树的最大深度 + ```csharp // 递归法 public int MaxDepth(TreeNode root) { @@ -1088,7 +1091,76 @@ public int MaxDepth(TreeNode root) } ``` +559.n叉树的最大深度 +递归法 +```csharp + /* + 递归法 + */ + public class Solution { + public int MaxDepth(Node root) { + int res = 0; + /* 终止条件 */ + if(root == null){ + return 0; + } + + /* logic */ + // 遍历当前节点的子节点 + for (int i = 0; i < root.children.Count; i++) + { + res = Math.Max(res, MaxDepth(root.children[i])); + } + return res + 1; + } + } + // @lc code=end +``` + 迭代法(层序遍历) +```csharp + /* + 迭代法 + */ + public class Solution + { + public int MaxDepth(Node root) + { + Queue que = new Queue(); // 使用泛型队列存储节点 + + int res = 0; + + if(root != null){ + que.Enqueue(root); // 将根节点加入队列 + } + while (que.Count > 0) + { + int size = que.Count; // 获取当前层的节点数 + res++; // 深度加一 + + for (int i = 0; i < size; i++) + { + // 每一层的遍历 + + var curNode = que.Dequeue(); // 取出队列中的节点 + for (int j = 0; j < curNode.children.Count; j++) + { + if (curNode.children[j] != null) + { + que.Enqueue(curNode.children[j]); // 将子节点加入队列 + } + } + } + } + + return res; // 返回树的最大深度 + + } + } +``` + +

+ From 8618c4491541b7ed4ef945952f1646909a6005d5 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 13 Jan 2024 10:50:06 +0800 Subject: [PATCH 025/118] =?UTF-8?q?Update=200062.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=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/0062.不同路径.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index 5131fdbb..207a66ee 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -536,8 +536,29 @@ object Solution { ``` ### c# +```csharp +// 二维数组 +public class Solution +{ + public int UniquePaths(int m, int n) + { + int[,] dp = new int[m, n]; + for (int i = 0; i < m; i++) dp[i, 0] = 1; + for (int j = 0; j < n; j++) dp[0, j] = 1; + for (int i = 1; i < m; i++) + { + for (int j = 1; j < n; j++) + { + dp[i, j] = dp[i - 1, j] + dp[i, j - 1]; + } + } + return dp[m - 1, n - 1]; + } +} +``` ```csharp +// 一维数组 public class Solution { public int UniquePaths(int m, int n) From 5fbb5fdc2ca45d5e210f4f7a043a9da52ca1a1d3 Mon Sep 17 00:00:00 2001 From: David Gao Date: Sat, 13 Jan 2024 20:44:21 -0500 Subject: [PATCH 026/118] =?UTF-8?q?0322.=E9=87=8D=E6=96=B0=E5=AE=89?= =?UTF-8?q?=E6=8E=92=E8=A1=8C=E7=A8=8B.md=20=E8=A7=A3=E5=86=B3python?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=9D=97=20=E5=9B=9E=E6=BA=AF=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E5=AD=97=E5=85=B8=E6=96=B9=E6=B3=95=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E8=B6=85=E6=97=B6=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 49 +++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 1473ed05..036cfc51 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -449,34 +449,37 @@ class Solution: ``` 回溯 使用字典 ```python -from collections import defaultdict - class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: - targets = defaultdict(list) # 构建机场字典 - for ticket in tickets: - targets[ticket[0]].append(ticket[1]) - for airport in targets: - targets[airport].sort() # 对目的地列表进行排序 + self.adj = {} - path = ["JFK"] # 起始机场为"JFK" - self.backtracking(targets, path, len(tickets)) - return path + # sort by the destination alphabetically + # 根据航班每一站的重点字母顺序排序 + tickets.sort(key=lambda x:x[1]) - def backtracking(self, targets, path, ticketNum): - if len(path) == ticketNum + 1: - return True # 找到有效行程 + # get all possible connection for each destination + # 罗列每一站的下一个可选项 + for u,v in tickets: + if u in self.adj: self.adj[u].append(v) + else: self.adj[u] = [v] - airport = path[-1] # 当前机场 - destinations = targets[airport] # 当前机场可以到达的目的地列表 - for i, dest in enumerate(destinations): - targets[airport].pop(i) # 标记已使用的机票 - path.append(dest) # 添加目的地到路径 - if self.backtracking(targets, path, ticketNum): - return True # 找到有效行程 - targets[airport].insert(i, dest) # 回溯,恢复机票 - path.pop() # 移除目的地 - return False # 没有找到有效行程 + # 从JFK出发 + self.result = [] + self.dfs("JFK") # start with JFK + + return self.result[::-1] # reverse to get the result + + def dfs(self, s): + # if depart city has flight and the flight can go to another city + while s in self.adj and len(self.adj[s]) > 0: + # 找到s能到哪里,选能到的第一个机场 + v = self.adj[s][0] # we go to the 1 choice of the city + # 在之后的可选项机场中去掉这个机场 + self.adj[s].pop(0) # get rid of this choice since we used it + # 从当前的新出发点开始 + self.dfs(v) # we start from the new airport + + self.result.append(s) # after append, it will back track to last node, thus the result list is in reversed order ``` 回溯 使用字典 逆序 From 08617fdff7d13cd4dcd8f512baccfdad5f64f766 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 14 Jan 2024 09:55:53 +0800 Subject: [PATCH 027/118] =?UTF-8?q?Update=200063.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=842=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/0063.不同路径II.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 8b842858..8c208ea8 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -734,6 +734,30 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int UniquePathsWithObstacles(int[][] obstacleGrid) + { + int m = obstacleGrid.Length; + int n = obstacleGrid[0].Length; + int[,] dp = new int[m, n]; + if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0; + for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i, 0] = 1; + for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0, j] = 1; + for (int i = 1; i < m; i++) + { + for (int j = 1; j < n; j++) + { + if (obstacleGrid[i][j] == 1) continue; + dp[i, j] = dp[i - 1, j] + dp[i, j - 1]; + } + } + return dp[m - 1, n - 1]; + } +} +```

From 0076152aecfff72cae6c53f4c36b29faee62e47d Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 15 Jan 2024 09:52:08 +0800 Subject: [PATCH 028/118] =?UTF-8?q?Update=200343.=E6=95=B4=E6=95=B0?= =?UTF-8?q?=E6=8B=86=E5=88=86=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/0343.整数拆分.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 2e17caf5..bbbd5c63 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -496,6 +496,25 @@ class Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int IntegerBreak(int n) + { + int[] dp = new int[n + 1]; + dp[2] = 1; + for (int i = 3; i <= n; i++) + { + for (int j = 1; j <= i / 2; j++) + { + dp[i] = Math.Max(dp[i],Math.Max(j*(i-j),j*dp[i-j])); + } + } + return dp[n]; + } +} +```

From 4f1c28d3c1f1ee32c78dd0a6c96f228895a92b25 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 10:36:33 +0800 Subject: [PATCH 029/118] =?UTF-8?q?Update=201020.=E9=A3=9E=E5=9C=B0?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E9=87=8F.md=20about=20golang?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1020.飞地的数量.md | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/problems/1020.飞地的数量.md b/problems/1020.飞地的数量.md index 29c237e5..679c1ca9 100644 --- a/problems/1020.飞地的数量.md +++ b/problems/1020.飞地的数量.md @@ -491,6 +491,60 @@ class Solution: return ans ``` +### Go + +dfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func numEnclaves(grid [][]int) int { + rows, cols := len(grid), len(grid[0]) + // 行 + for i := range grid[0] { + if grid[0][i] == 1 { + dfs(grid, 0, i) + } + if grid[rows-1][i] == 1 { + dfs(grid, rows-1, i) + } + } + // 列 + for j := range grid { + if grid[j][0] == 1 { + dfs(grid, j, 0) + } + if grid[j][cols-1] == 1 { + dfs(grid, j, cols-1) + } + } + count = 0 + for i := range grid { + for j := range grid[0] { + if grid[i][j] == 1 { + dfs(grid, i, j) + } + } + } + return count +} + +func dfs(grid [][]int, i, j int) { + grid[i][j] = 0 + count++ + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == 1 { + dfs(grid, x, y) + } + } +} +``` + ### Rust dfs: From 8823181498afb51aac908159d0cb1b31caa5b1fc Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 10:41:57 +0800 Subject: [PATCH 030/118] =?UTF-8?q?Update=201020.=E9=A3=9E=E5=9C=B0?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E9=87=8F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1020.飞地的数量.md | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/problems/1020.飞地的数量.md b/problems/1020.飞地的数量.md index 679c1ca9..3488777a 100644 --- a/problems/1020.飞地的数量.md +++ b/problems/1020.飞地的数量.md @@ -545,6 +545,66 @@ func dfs(grid [][]int, i, j int) { } ``` +bfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} +var count int = 0 + +func numEnclaves(grid [][]int) int { + rows, cols := len(grid), len(grid[0]) + // 行 + for i := range grid[0] { + if grid[0][i] == 1 { + bfs(grid, 0, i) + } + if grid[rows-1][i] == 1 { + bfs(grid, rows-1, i) + } + } + // 列 + for j := range grid { + if grid[j][0] == 1 { + bfs(grid, j, 0) + } + if grid[j][cols-1] == 1 { + bfs(grid, j, cols-1) + } + } + count = 0 + for i := range grid { + for j := range grid[0] { + if grid[i][j] == 1 { + bfs(grid, i, j) + } + } + } + return count +} + +func bfs(grid [][]int, i, j int) { + queue := [][]int{} + queue = append(queue, []int{i, j}) + grid[i][j] = 0 + count++ + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) { + continue + } + if grid[x][y] == 1 { + count++ + queue = append(queue, []int{x, y}) + grid[x][y] = 0 + } + } + } +} +``` + ### Rust dfs: From 73c06613f7f9614df170667aa6bef87f0dcca3d4 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 17:24:43 +0800 Subject: [PATCH 031/118] =?UTF-8?q?Update=200130.=E8=A2=AB=E5=9B=B4?= =?UTF-8?q?=E7=BB=95=E7=9A=84=E5=8C=BA=E5=9F=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0130.被围绕的区域.md | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0130.被围绕的区域.md b/problems/0130.被围绕的区域.md index 8014c0c8..e2185a17 100644 --- a/problems/0130.被围绕的区域.md +++ b/problems/0130.被围绕的区域.md @@ -561,6 +561,58 @@ function solve(board) { } ``` +### Go + +```dfs +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + +func solve(board [][]byte) { + rows, cols := len(board), len(board[0]) + // 列 + for i := 0; i < rows; i++ { + if board[i][0] == 'O' { + dfs(board, i, 0) + } + if board[i][cols-1] == 'O' { + dfs(board, i, cols-1) + } + } + // 行 + for j := 0; j < cols; j++ { + if board[0][j] == 'O' { + dfs(board, 0, j) + } + if board[rows-1][j] == 'O' { + dfs(board, rows-1, j) + } + } + + for _, r := range board { + for j, c := range r { + if c == 'A' { + r[j] = 'O' + } + if c == 'O' { + r[j] = 'X' + } + } + } +} + +func dfs(board [][]byte, i, j int) { + board[i][j] = 'A' + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(board) || y < 0 || y >= len(board[0]) { + continue + } + if board[x][y] == 'O' { + dfs(board, x, y) + } + } +} +``` +

From 52496f8fd6e65aa5073f48fcc6a545f18dffd218 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 17:29:34 +0800 Subject: [PATCH 032/118] =?UTF-8?q?Update=200130.=E8=A2=AB=E5=9B=B4?= =?UTF-8?q?=E7=BB=95=E7=9A=84=E5=8C=BA=E5=9F=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0130.被围绕的区域.md | 62 ++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/problems/0130.被围绕的区域.md b/problems/0130.被围绕的区域.md index e2185a17..352face8 100644 --- a/problems/0130.被围绕的区域.md +++ b/problems/0130.被围绕的区域.md @@ -563,7 +563,9 @@ function solve(board) { ### Go -```dfs +dfs: + +```go var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} func solve(board [][]byte) { @@ -613,6 +615,64 @@ func dfs(board [][]byte, i, j int) { } ``` +bfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + +func solve(board [][]byte) { + rows, cols := len(board), len(board[0]) + // 列 + for i := 0; i < rows; i++ { + if board[i][0] == 'O' { + bfs(board, i, 0) + } + if board[i][cols-1] == 'O' { + bfs(board, i, cols-1) + } + } + // 行 + for j := 0; j < cols; j++ { + if board[0][j] == 'O' { + bfs(board, 0, j) + } + if board[rows-1][j] == 'O' { + bfs(board, rows-1, j) + } + } + + for _, r := range board { + for j, c := range r { + if c == 'A' { + r[j] = 'O' + } + if c == 'O' { + r[j] = 'X' + } + } + } +} + +func bfs(board [][]byte, i, j int) { + queue := [][]int{{i, j}} + board[i][j] = 'A' + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(board) || y < 0 || y >= len(board[0]) { + continue + } + if board[x][y] == 'O' { + board[x][y] = 'A' + queue = append(queue, []int{x, y}) + } + } + } +} +``` +

From 69377ddec1366c81dbe9343147e2c64de7bf3368 Mon Sep 17 00:00:00 2001 From: maolu Date: Mon, 15 Jan 2024 17:48:20 +0800 Subject: [PATCH 033/118] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E6=96=B0=E8=A7=A3?= =?UTF-8?q?=E6=B3=95=EF=BC=9A=E8=9E=BA=E6=97=8B=E7=9F=A9=E9=98=B5=E5=AE=9A?= =?UTF-8?q?=E4=B9=894=E4=B8=AA=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 8 ++++ .idea/encodings.xml | 4 ++ .../inspectionProfiles/profiles_settings.xml | 6 +++ .idea/leetcode-master.iml | 8 ++++ .idea/misc.xml | 4 ++ .idea/modules.xml | 8 ++++ .idea/vcs.xml | 6 +++ problems/0054.螺旋矩阵.md | 41 +++++++++++++++++ problems/0059.螺旋矩阵II.md | 44 +++++++++++++++++++ 9 files changed, 129 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/encodings.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/leetcode-master.iml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 00000000..15a15b21 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 00000000..105ce2da --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/leetcode-master.iml b/.idea/leetcode-master.iml new file mode 100644 index 00000000..d0876a78 --- /dev/null +++ b/.idea/leetcode-master.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..4d519243 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..7c250acd --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 44a7749d..85e6a936 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -306,6 +306,47 @@ class Solution(object): return result ``` +版本二:定义四个边界 +```python +class Solution(object): + def spiralOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + if not matrix: + return [] + + rows = len(matrix) + cols = len(matrix[0]) + top, bottom, left, right = 0, rows - 1, 0, cols - 1 + print_list = [] + + while top <= bottom and left <= right: + # 从左到右 + for i in range(left, right + 1): + print_list.append(matrix[top][i]) + top += 1 + + # 从上到下 + for i in range(top, bottom + 1): + print_list.append(matrix[i][right]) + right -= 1 + + # 从右到左 + if top <= bottom: + for i in range(right, left - 1, -1): + print_list.append(matrix[bottom][i]) + bottom -= 1 + + # 从下到上 + if left <= right: + for i in range(bottom, top - 1, -1): + print_list.append(matrix[i][left]) + left += 1 + + return print_list +```

diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 58378ffc..8823a0d8 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -207,6 +207,50 @@ class Solution: return nums ``` +版本二:定义四个边界 +```python +class Solution(object): + def generateMatrix(self, n): + if n <= 0: + return [] + + # 初始化 n x n 矩阵 + matrix = [[0]*n for _ in range(n)] + + # 初始化边界和起始值 + top, bottom, left, right = 0, n-1, 0, n-1 + num = 1 + + while top <= bottom and left <= right: + # 从左到右填充上边界 + for i in range(left, right + 1): + matrix[top][i] = num + num += 1 + top += 1 + + # 从上到下填充右边界 + for i in range(top, bottom + 1): + matrix[i][right] = num + num += 1 + right -= 1 + + # 从右到左填充下边界 + + for i in range(right, left - 1, -1): + matrix[bottom][i] = num + num += 1 + bottom -= 1 + + # 从下到上填充左边界 + + for i in range(bottom, top - 1, -1): + matrix[i][left] = num + num += 1 + left += 1 + + return matrix +``` + ### JavaScript: ```javascript From 0e34b46a1777988cf1e618d4e227d02b7f1a82ae Mon Sep 17 00:00:00 2001 From: maolu Date: Mon, 15 Jan 2024 18:03:02 +0800 Subject: [PATCH 034/118] =?UTF-8?q?=E5=88=A0=E9=99=A4.idea?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 8 -------- .idea/encodings.xml | 4 ---- .idea/inspectionProfiles/profiles_settings.xml | 6 ------ .idea/leetcode-master.iml | 8 -------- .idea/misc.xml | 4 ---- .idea/modules.xml | 8 -------- .idea/vcs.xml | 6 ------ 7 files changed, 44 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/encodings.xml delete mode 100644 .idea/inspectionProfiles/profiles_settings.xml delete mode 100644 .idea/leetcode-master.iml delete mode 100644 .idea/misc.xml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/vcs.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b81..00000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index 15a15b21..00000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2da..00000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/leetcode-master.iml b/.idea/leetcode-master.iml deleted file mode 100644 index d0876a78..00000000 --- a/.idea/leetcode-master.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 4d519243..00000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 7c250acd..00000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1ddf..00000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 47688ba24829cab212fa9d3d911199cbe8afee57 Mon Sep 17 00:00:00 2001 From: Chenxue3 <71321839+Chenxue3@users.noreply.github.com> Date: Mon, 15 Jan 2024 23:10:46 +1300 Subject: [PATCH 035/118] =?UTF-8?q?Update=200513.=E6=89=BE=E6=A0=91?= =?UTF-8?q?=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC.md=20-=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0C#=E8=BF=AD=E4=BB=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0513.找树左下角的值.md | 48 ++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 3cdcc801..d897bba1 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -716,9 +716,55 @@ public void Traversal(TreeNode root, int depth) return; } ``` +```csharp +/* + * @lc app=leetcode id=513 lang=csharp + * 迭代法 + * [513] Find Bottom Left Tree Value + */ + +// @lc code=start +public class Solution +{ + public int FindBottomLeftValue(TreeNode root) + { + Queue que = new Queue(); + + if (root != null) + { + que.Enqueue(root); + } + + int ans = 0; + while (que.Count != 0) + { + + int size = que.Count; + for (var i = 0; i < size; i++) + { + var curNode = que.Peek(); + que.Dequeue(); + if(i == 0){ + ans = curNode.val; + } + if (curNode.left != null) + { + que.Enqueue(curNode.left); + } + if (curNode.right != null) + { + que.Enqueue(curNode.right); + } + } + + } + return ans; + } +} +// @lc code=end +```

- From 5ad279f73717ba8c7194a0b238a8bb5a0d97b2e7 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 18:11:30 +0800 Subject: [PATCH 036/118] =?UTF-8?q?Update=200130.=E8=A2=AB=E5=9B=B4?= =?UTF-8?q?=E7=BB=95=E7=9A=84=E5=8C=BA=E5=9F=9F.md=20for=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0130.被围绕的区域.md | 119 ++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/problems/0130.被围绕的区域.md b/problems/0130.被围绕的区域.md index 352face8..1ddaaa7f 100644 --- a/problems/0130.被围绕的区域.md +++ b/problems/0130.被围绕的区域.md @@ -593,6 +593,7 @@ func solve(board [][]byte) { for j, c := range r { if c == 'A' { r[j] = 'O' + continue } if c == 'O' { r[j] = 'X' @@ -645,6 +646,7 @@ func solve(board [][]byte) { for j, c := range r { if c == 'A' { r[j] = 'O' + continue } if c == 'O' { r[j] = 'X' @@ -673,6 +675,123 @@ func bfs(board [][]byte, i, j int) { } ``` +### Rust + +bfs: + +```rust +impl Solution { + const DIRECTIONS: [(isize, isize); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)]; + pub fn solve(board: &mut Vec>) { + let (rows, cols) = (board.len(), board[0].len()); + // 列 + for i in 0..rows { + if board[i][0] == 'O' { + Self::dfs(board, i, 0); + } + if board[i][cols - 1] == 'O' { + Self::dfs(board, i, cols - 1); + } + } + //行 + for j in 0..cols { + if board[0][j] == 'O' { + Self::dfs(board, 0, j); + } + if board[rows - 1][j] == 'O' { + Self::dfs(board, rows - 1, j); + } + } + + for v in board.iter_mut() { + for c in v.iter_mut() { + if *c == 'A' { + *c = 'O'; + continue; + } + if *c == 'O' { + *c = 'X'; + } + } + } + } + + pub fn dfs(board: &mut [Vec], i: usize, j: usize) { + board[i][j] = 'A'; + for (d1, d2) in Self::DIRECTIONS { + let (x, y) = (i as isize + d1, j as isize + d2); + if x < 0 || x >= board.len() as isize || y < 0 || y >= board[0].len() as isize { + continue; + } + let (x, y) = (x as usize, y as usize); + if board[x][y] == 'O' { + Self::dfs(board, x, y); + } + } + } +} +``` + +bfs: + +```rust +use std::collections::VecDeque; +impl Solution { + const DIRECTIONS: [(isize, isize); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)]; + pub fn solve(board: &mut Vec>) { + let (rows, cols) = (board.len(), board[0].len()); + // 列 + for i in 0..rows { + if board[i][0] == 'O' { + Self::bfs(board, i, 0); + } + if board[i][cols - 1] == 'O' { + Self::bfs(board, i, cols - 1); + } + } + //行 + for j in 0..cols { + if board[0][j] == 'O' { + Self::bfs(board, 0, j); + } + if board[rows - 1][j] == 'O' { + Self::bfs(board, rows - 1, j); + } + } + + for v in board.iter_mut() { + for c in v.iter_mut() { + if *c == 'A' { + *c = 'O'; + continue; + } + if *c == 'O' { + *c = 'X'; + } + } + } + } + + pub fn bfs(board: &mut [Vec], i: usize, j: usize) { + let mut queue = VecDeque::from([(i, j)]); + board[i][j] = 'A'; + while let Some((i, j)) = queue.pop_front() { + for (d1, d2) in Self::DIRECTIONS { + let (x, y) = (i as isize + d1, j as isize + d2); + if x < 0 || x >= board.len() as isize || y < 0 || y >= board[0].len() as isize { + continue; + } + let (x, y) = (x as usize, y as usize); + if board[x][y] == 'O' { + board[x][y] = 'A'; + queue.push_back((x, y)); + } + } + } + } +} +``` +

From c6d7c78dee47ee1eded34779c53227c3f49eeef8 Mon Sep 17 00:00:00 2001 From: Chenxue3 <71321839+Chenxue3@users.noreply.github.com> Date: Tue, 16 Jan 2024 01:37:06 +1300 Subject: [PATCH 037/118] =?UTF-8?q?0112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md=20=E6=B7=BB=E5=8A=A00113=20=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=80=BB=E5=92=8CII=20C#=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 56 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 28134a7c..d45be3bd 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -1523,8 +1523,64 @@ public bool HasPathSum(TreeNode root, int targetSum) return HasPathSum(root.left, targetSum - root.val) || HasPathSum(root.right, targetSum - root.val); } ``` +0113.路径总和: +```csharp +/* + * @lc app=leetcode id=113 lang=csharp + * 0113.路径总和 II + * [113] Path Sum II + * 递归法 + */ +public class Solution { + private List> result = new List>(); + private List path = new List(); + // Main function to find paths with the given sum + public IList> PathSum(TreeNode root, int targetSum) { + result.Clear(); + path.Clear(); + if (root == null) return result.Select(list => list as IList).ToList(); + path.Add(root.val); // Add the root node to the path + traversal(root, targetSum - root.val); // Start the traversal + return result.Select(list => list as IList).ToList(); + } + + // Recursive function to traverse the tree and find paths + private void traversal(TreeNode node, int count) { + // If a leaf node is reached and the target sum is achieved + if (node.left == null && node.right == null && count == 0) { + result.Add(new List(path)); // Add a copy of the path to the result + return; + } + + // If a leaf node is reached and the target sum is not achieved, or if it's not a leaf node + if (node.left == null && node.right == null) return; + + // Traverse the left subtree + if (node.left != null) { + path.Add(node.left.val); + count -= node.left.val; + traversal(node.left, count); // Recursive call + count += node.left.val; // Backtrack + path.RemoveAt(path.Count - 1); // Backtrack + } + + // Traverse the right subtree + if (node.right != null) { + path.Add(node.right.val); + count -= node.right.val; + traversal(node.right, count); // Recursive call + count += node.right.val; // Backtrack + path.RemoveAt(path.Count - 1); // Backtrack + } + } +} + +// @lc code=end + +```

+ From 57025dcf3765174b867bc9710b57acf8a85b5a92 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Tue, 16 Jan 2024 11:11:28 +0800 Subject: [PATCH 038/118] =?UTF-8?q?Update=200096.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=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/0096.不同的二叉搜索树.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index d109165b..15b99083 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -328,6 +328,25 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int NumTrees(int n) + { + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int i = 1; i <= n; i++) + { + for (int j = 1; j <= i; j++) + { + dp[i] += dp[j - 1] * dp[i - j]; + } + } + return dp[n]; + } +} +```

From b19b832edf8cbe20ce3a9736e292c06b9d4fe979 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Tue, 16 Jan 2024 14:00:17 +0800 Subject: [PATCH 039/118] =?UTF-8?q?Update=200417.=E5=A4=AA=E5=B9=B3?= =?UTF-8?q?=E6=B4=8B=E5=A4=A7=E8=A5=BF=E6=B4=8B=E6=B0=B4=E6=B5=81=E9=97=AE?= =?UTF-8?q?=E9=A2=98.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0417.太平洋大西洋水流问题.md | 102 ++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/problems/0417.太平洋大西洋水流问题.md b/problems/0417.太平洋大西洋水流问题.md index 53ae14ed..21f8a1ca 100644 --- a/problems/0417.太平洋大西洋水流问题.md +++ b/problems/0417.太平洋大西洋水流问题.md @@ -562,7 +562,109 @@ function pacificAtlantic(heights) { } ``` +### go +dfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} + +func pacificAtlantic(heights [][]int) [][]int { + res := make([][]int, 0) + pacific := make([][]bool, len(heights)) + atlantic := make([][]bool, len(heights)) + for i := 0; i < len(heights); i++ { + pacific[i] = make([]bool, len(heights[0])) + atlantic[i] = make([]bool, len(heights[0])) + } + // 列 + for i := 0; i < len(heights); i++ { + dfs(heights, pacific, i, 0) + dfs(heights, atlantic, i, len(heights[0])-1) + } + // 行 + for j := 0; j < len(heights[0]); j++ { + dfs(heights, pacific, 0, j) + dfs(heights, atlantic, len(heights)-1, j) + } + + for i := 0; i < len(heights); i++ { + for j := 0; j < len(heights[0]); j++ { + if pacific[i][j] && atlantic[i][j] { + res = append(res, []int{i, j}) + } + } + } + + return res +} + +func dfs(heights [][]int, visited [][]bool, i, j int) { + visited[i][j] = true + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(heights) || y < 0 || y >= len(heights[0]) || heights[i][j] > heights[x][y] || visited[x][y] { + continue + } + + dfs(heights, visited, x, y) + } +} +``` + +bfs: + +```go +var DIRECTIONS = [4][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} + +func pacificAtlantic(heights [][]int) [][]int { + res := make([][]int, 0) + pacific := make([][]bool, len(heights)) + atlantic := make([][]bool, len(heights)) + for i := 0; i < len(heights); i++ { + pacific[i] = make([]bool, len(heights[0])) + atlantic[i] = make([]bool, len(heights[0])) + } + // 列 + for i := 0; i < len(heights); i++ { + bfs(heights, pacific, i, 0) + bfs(heights, atlantic, i, len(heights[0])-1) + } + // 行 + for j := 0; j < len(heights[0]); j++ { + bfs(heights, pacific, 0, j) + bfs(heights, atlantic, len(heights)-1, j) + } + + for i := 0; i < len(heights); i++ { + for j := 0; j < len(heights[0]); j++ { + if pacific[i][j] && atlantic[i][j] { + res = append(res, []int{i, j}) + } + } + } + + return res +} + +func bfs(heights [][]int, visited [][]bool, i, j int) { + queue := make([][]int, 0) + queue = append(queue, []int{i, j}) + visited[i][j] = true + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, d := range DIRECTIONS { + x, y := cur[0]+d[0], cur[1]+d[1] + if x < 0 || x >= len(heights) || y < 0 || y >= len(heights[0]) || heights[cur[0]][cur[1]] > heights[x][y] || visited[x][y] { + continue + } + queue = append(queue, []int{x, y}) + visited[x][y] = true + } + } +} +```

From f9c2d9677bdf6432c87b4c91b4596fc634599c93 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Tue, 16 Jan 2024 14:35:10 +0800 Subject: [PATCH 040/118] =?UTF-8?q?Update=200417.=E5=A4=AA=E5=B9=B3?= =?UTF-8?q?=E6=B4=8B=E5=A4=A7=E8=A5=BF=E6=B4=8B=E6=B0=B4=E6=B5=81=E9=97=AE?= =?UTF-8?q?=E9=A2=98.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0417.太平洋大西洋水流问题.md | 104 ++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/problems/0417.太平洋大西洋水流问题.md b/problems/0417.太平洋大西洋水流问题.md index 21f8a1ca..8fe0f1b4 100644 --- a/problems/0417.太平洋大西洋水流问题.md +++ b/problems/0417.太平洋大西洋水流问题.md @@ -666,6 +666,110 @@ func bfs(heights [][]int, visited [][]bool, i, j int) { } ``` +### Rust + +dfs: + +```rust +impl Solution { + const DIRECTIONS: [(isize, isize); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)]; + pub fn pacific_atlantic(heights: Vec>) -> Vec> { + let (m, n) = (heights.len(), heights[0].len()); + let mut res = vec![]; + let (mut pacific, mut atlantic) = (vec![vec![false; n]; m], vec![vec![false; n]; m]); + + // 列 + for i in 0..m { + Self::dfs(&heights, &mut pacific, i, 0); + Self::dfs(&heights, &mut atlantic, i, n - 1); + } + + for j in 0..n { + Self::dfs(&heights, &mut pacific, 0, j); + Self::dfs(&heights, &mut atlantic, m - 1, j); + } + + for i in 0..m { + for j in 0..n { + if pacific[i][j] && atlantic[i][j] { + res.push(vec![i as i32, j as i32]); + } + } + } + + res + } + + pub fn dfs(heights: &[Vec], visited: &mut [Vec], i: usize, j: usize) { + visited[i][j] = true; + for (dx, dy) in Self::DIRECTIONS { + let (x, y) = (i as isize + dx, j as isize + dy); + if x < 0 || x >= heights.len() as isize || y < 0 || y >= heights[0].len() as isize { + continue; + } + let (x, y) = (x as usize, y as usize); + if !visited[x][y] && heights[x][y] >= heights[i][j] { + Self::dfs(heights, visited, x, y); + } + } + } +} +``` + +bfs: + +```rust +use std::collections::VecDeque; + +impl Solution { + const DIRECTIONS: [(isize, isize); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)]; + pub fn pacific_atlantic(heights: Vec>) -> Vec> { + let (m, n) = (heights.len(), heights[0].len()); + let mut res = vec![]; + let (mut pacific, mut atlantic) = (vec![vec![false; n]; m], vec![vec![false; n]; m]); + + // 列 + for i in 0..m { + Self::bfs(&heights, &mut pacific, i, 0); + Self::bfs(&heights, &mut atlantic, i, n - 1); + } + + for j in 0..n { + Self::bfs(&heights, &mut pacific, 0, j); + Self::bfs(&heights, &mut atlantic, m - 1, j); + } + + for i in 0..m { + for j in 0..n { + if pacific[i][j] && atlantic[i][j] { + res.push(vec![i as i32, j as i32]); + } + } + } + + res + } + + pub fn bfs(heights: &[Vec], visited: &mut [Vec], i: usize, j: usize) { + let mut queue = VecDeque::from([(i, j)]); + visited[i][j] = true; + while let Some((i, j)) = queue.pop_front() { + for (dx, dy) in Self::DIRECTIONS { + let (x, y) = (i as isize + dx, j as isize + dy); + if x < 0 || x >= heights.len() as isize || y < 0 || y >= heights[0].len() as isize { + continue; + } + let (x, y) = (x as usize, y as usize); + if !visited[x][y] && heights[x][y] >= heights[i][j] { + queue.push_back((x, y)); + visited[x][y] = true; + } + } + } + } +} +``` +

From 480d0d1f281e4ec87ff206cd399e469284fe8fca Mon Sep 17 00:00:00 2001 From: Yao Zu <1796381757@qq.com> Date: Tue, 16 Jan 2024 20:52:46 +0800 Subject: [PATCH 041/118] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200383.=E8=B5=8E?= =?UTF-8?q?=E9=87=91=E4=BF=A1.md=20Python=E7=89=88=E6=9C=AC=E5=85=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原代码块语言为python3,代码随想录网站无法正常渲染,改为python --- problems/0383.赎金信.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index b800c232..93ade51e 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -216,7 +216,7 @@ class Solution: (版本六)使用count(简单易懂) -```python3 +```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for char in ransomNote: From 064e582b1e74826e3b60b379aff9c3ee3c41d689 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Wed, 17 Jan 2024 10:37:45 +0800 Subject: [PATCH 042/118] =?UTF-8?q?Update=200416.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E7=AD=89=E5=92=8C=E5=AD=90=E9=9B=86=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/0416.分割等和子集.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 81eb4c80..71e01ae3 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -726,7 +726,35 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public bool CanPartition(int[] nums) + { + int sum = 0; + int[] dp = new int[10001]; + foreach (int num in nums) + { + sum += num; + } + if (sum % 2 == 1) return false; + int tartget = sum / 2; + for (int i = 0; i < nums.Length; i++) + { + for (int j = tartget; j >= nums[i]; j--) + { + dp[j] = Math.Max(dp[j], dp[j - nums[i]] + nums[i]); + } + } + if (dp[tartget] == tartget) + return true; + return false; + + } +} +```

From f0ac6f599c459a87c96f3adda3f9dce898bef810 Mon Sep 17 00:00:00 2001 From: WmW Date: Wed, 17 Jan 2024 10:48:03 +0800 Subject: [PATCH 043/118] =?UTF-8?q?update:=200435.=E6=97=A0=E9=87=8D?= =?UTF-8?q?=E5=8F=A0=E5=8C=BA=E9=97=B4=EF=BC=8Crust=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0435.无重叠区间.md | 191 +++++++++++++++++++----------------- 1 file changed, 103 insertions(+), 88 deletions(-) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 1a33f98e..0bfda5fc 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -4,7 +4,6 @@

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

- # 435. 无重叠区间 [力扣题目链接](https://leetcode.cn/problems/non-overlapping-intervals/) @@ -16,19 +15,22 @@ 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 示例 1: -* 输入: [ [1,2], [2,3], [3,4], [1,3] ] -* 输出: 1 -* 解释: 移除 [1,3] 后,剩下的区间没有重叠。 + +- 输入: [ [1,2], [2,3], [3,4], [1,3] ] +- 输出: 1 +- 解释: 移除 [1,3] 后,剩下的区间没有重叠。 示例 2: -* 输入: [ [1,2], [1,2], [1,2] ] -* 输出: 2 -* 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 + +- 输入: [ [1,2], [1,2], [1,2] ] +- 输出: 2 +- 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 示例 3: -* 输入: [ [1,2], [2,3] ] -* 输出: 0 -* 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 + +- 输入: [ [1,2], [2,3] ] +- 输出: 0 +- 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 ## 算法公开课 @@ -38,7 +40,7 @@ **相信很多同学看到这道题目都冥冥之中感觉要排序,但是究竟是按照右边界排序,还是按照左边界排序呢?** -其实都可以。主要就是为了让区间尽可能的重叠。 +其实都可以。主要就是为了让区间尽可能的重叠。 **我来按照右边界排序,从左向右记录非交叉区间的个数。最后用区间总数减去非交叉区间的个数就是需要移除的区间个数了**。 @@ -48,17 +50,17 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230201164134.png) -区间,1,2,3,4,5,6都按照右边界排好序。 +区间,1,2,3,4,5,6 都按照右边界排好序。 -当确定区间 1 和 区间2 重叠后,如何确定是否与 区间3 也重贴呢? +当确定区间 1 和 区间 2 重叠后,如何确定是否与 区间 3 也重贴呢? -就是取 区间1 和 区间2 右边界的最小值,因为这个最小值之前的部分一定是 区间1 和区间2 的重合部分,如果这个最小值也触达到区间3,那么说明 区间 1,2,3都是重合的。 +就是取 区间 1 和 区间 2 右边界的最小值,因为这个最小值之前的部分一定是 区间 1 和区间 2 的重合部分,如果这个最小值也触达到区间 3,那么说明 区间 1,2,3 都是重合的。 -接下来就是找大于区间1结束位置的区间,是从区间4开始。**那有同学问了为什么不从区间5开始?别忘了已经是按照右边界排序的了**。 +接下来就是找大于区间 1 结束位置的区间,是从区间 4 开始。**那有同学问了为什么不从区间 5 开始?别忘了已经是按照右边界排序的了**。 -区间4结束之后,再找到区间6,所以一共记录非交叉区间的个数是三个。 +区间 4 结束之后,再找到区间 6,所以一共记录非交叉区间的个数是三个。 -总共区间个数为6,减去非交叉区间的个数3。移除区间的最小数量就是3。 +总共区间个数为 6,减去非交叉区间的个数 3。移除区间的最小数量就是 3。 C++代码如下: @@ -84,8 +86,9 @@ public: } }; ``` -* 时间复杂度:O(nlog n) ,有一个快排 -* 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间 + +- 时间复杂度:O(nlog n) ,有一个快排 +- 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要 n 次递归调用。因此确实需要 O(n)的栈空间 大家此时会发现如此复杂的一个问题,代码实现却这么简单! @@ -93,11 +96,11 @@ public: ### 补充(1) -左边界排序可不可以呢? +左边界排序可不可以呢? -也是可以的,只不过 左边界排序我们就是直接求 重叠的区间,count为记录重叠区间数。 +也是可以的,只不过 左边界排序我们就是直接求 重叠的区间,count 为记录重叠区间数。 -```CPP +```CPP class Solution { public: static bool cmp (const vector& a, const vector& b) { @@ -108,9 +111,9 @@ public: sort(intervals.begin(), intervals.end(), cmp); int count = 0; // 注意这里从0开始,因为是记录重叠区间 int end = intervals[0][1]; // 记录区间分割点 - for (int i = 1; i < intervals.size(); i++) { + for (int i = 1; i < intervals.size(); i++) { if (intervals[i][0] >= end) end = intervals[i][1]; // 无重叠的情况 - else { // 重叠情况 + else { // 重叠情况 end = min(end, intervals[i][1]); count++; } @@ -120,9 +123,9 @@ public: }; ``` -其实代码还可以精简一下, 用 intervals[i][1] 替代 end变量,只判断 重叠情况就好 +其实代码还可以精简一下, 用 intervals[i][1] 替代 end 变量,只判断 重叠情况就好 -```CPP +```CPP class Solution { public: static bool cmp (const vector& a, const vector& b) { @@ -148,14 +151,14 @@ public: 本题其实和[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)非常像,弓箭的数量就相当于是非交叉区间的数量,只要把弓箭那道题目代码里射爆气球的判断条件加个等号(认为[0,1][1,2]不是相邻区间),然后用总区间数减去弓箭数量 就是要移除的区间数量了。 -把[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)代码稍做修改,就可以AC本题。 +把[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)代码稍做修改,就可以 AC 本题。 ```CPP class Solution { public: // 按照区间右边界排序 static bool cmp (const vector& a, const vector& b) { - return a[1] < b[1]; // 右边界排序 + return a[1] < b[1]; // 右边界排序 } int eraseOverlapIntervals(vector>& intervals) { if (intervals.size() == 0) return 0; @@ -175,7 +178,8 @@ public: }; ``` -这里按照 左边界排序,或者按照右边界排序,都可以AC,原理是一样的。 +这里按照 左边界排序,或者按照右边界排序,都可以 AC,原理是一样的。 + ```CPP class Solution { public: @@ -204,8 +208,8 @@ public: ## 其他语言版本 +### Java -### Java ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -219,7 +223,7 @@ class Solution { continue; }else{ count++; - } + } } return intervals.length - count; } @@ -227,6 +231,7 @@ class Solution { ``` 按左边排序,不管右边顺序。相交的时候取最小的右边。 + ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -247,47 +252,53 @@ class Solution { } ``` -### Python +### Python + 贪心 基于左边界 + ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 - + intervals.sort(key=lambda x: x[0]) # 按照左边界升序排序 count = 0 # 记录重叠区间数量 - + for i in range(1, len(intervals)): if intervals[i][0] < intervals[i - 1][1]: # 存在重叠区间 intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]) # 更新重叠区间的右边界 count += 1 - + return count ``` -贪心 基于左边界 把452.用最少数量的箭引爆气球代码稍做修改 + +贪心 基于左边界 把 452.用最少数量的箭引爆气球代码稍做修改 + ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 - + intervals.sort(key=lambda x: x[0]) # 按照左边界升序排序 - + result = 1 # 不重叠区间数量,初始化为1,因为至少有一个不重叠的区间 - + for i in range(1, len(intervals)): if intervals[i][0] >= intervals[i - 1][1]: # 没有重叠 result += 1 else: # 重叠情况 intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]) # 更新重叠区间的右边界 - + return len(intervals) - result ``` -### Go + +### Go + ```go func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -312,7 +323,9 @@ func min(a, b int) int { ``` ### Javascript + - 按右边界排序 + ```Javascript var eraseOverlapIntervals = function(intervals) { intervals.sort((a, b) => { @@ -329,27 +342,29 @@ var eraseOverlapIntervals = function(intervals) { count += 1 } } - + return intervals.length - count }; ``` + - 按左边界排序 + ```js -var eraseOverlapIntervals = function(intervals) { - // 按照左边界升序排列 - intervals.sort((a, b) => a[0] - b[0]) - let count = 1 - let end = intervals[intervals.length - 1][0] - // 倒序遍历,对单个区间来说,左边界越大越好,因为给前面区间的空间越大 - for(let i = intervals.length - 2; i >= 0; i--) { - if(intervals[i][1] <= end) { - count++ - end = intervals[i][0] - } +var eraseOverlapIntervals = function (intervals) { + // 按照左边界升序排列 + intervals.sort((a, b) => a[0] - b[0]); + let count = 1; + let end = intervals[intervals.length - 1][0]; + // 倒序遍历,对单个区间来说,左边界越大越好,因为给前面区间的空间越大 + for (let i = intervals.length - 2; i >= 0; i--) { + if (intervals[i][1] <= end) { + count++; + end = intervals[i][0]; } - // count 记录的是最大非重复区间的个数 - return intervals.length - count -} + } + // count 记录的是最大非重复区间的个数 + return intervals.length - count; +}; ``` ### TypeScript @@ -358,43 +373,43 @@ var eraseOverlapIntervals = function(intervals) { ```typescript function eraseOverlapIntervals(intervals: number[][]): number { - const length = intervals.length; - if (length === 0) return 0; - intervals.sort((a, b) => a[1] - b[1]); - let right: number = intervals[0][1]; - let count: number = 1; - for (let i = 1; i < length; i++) { - if (intervals[i][0] >= right) { - count++; - right = intervals[i][1]; - } + const length = intervals.length; + if (length === 0) return 0; + intervals.sort((a, b) => a[1] - b[1]); + let right: number = intervals[0][1]; + let count: number = 1; + for (let i = 1; i < length; i++) { + if (intervals[i][0] >= right) { + count++; + right = intervals[i][1]; } - return length - count; -}; + } + return length - count; +} ``` > 按左边界排序,从左往右遍历 ```typescript function eraseOverlapIntervals(intervals: number[][]): number { - if (intervals.length === 0) return 0; - intervals.sort((a, b) => a[0] - b[0]); - let right: number = intervals[0][1]; - let tempInterval: number[]; - let resCount: number = 0; - for (let i = 1, length = intervals.length; i < length; i++) { - tempInterval = intervals[i]; - if (tempInterval[0] >= right) { - // 未重叠 - right = tempInterval[1]; - } else { - // 有重叠,移除当前interval和前一个interval中右边界更大的那个 - right = Math.min(right, tempInterval[1]); - resCount++; - } + if (intervals.length === 0) return 0; + intervals.sort((a, b) => a[0] - b[0]); + let right: number = intervals[0][1]; + let tempInterval: number[]; + let resCount: number = 0; + for (let i = 1, length = intervals.length; i < length; i++) { + tempInterval = intervals[i]; + if (tempInterval[0] >= right) { + // 未重叠 + right = tempInterval[1]; + } else { + // 有重叠,移除当前interval和前一个interval中右边界更大的那个 + right = Math.min(right, tempInterval[1]); + resCount++; } - return resCount; -}; + } + return resCount; +} ``` ### Scala @@ -423,7 +438,7 @@ object Solution { ```Rust impl Solution { - pub fn erase_overlap_intervals(intervals: Vec>) -> i32 { + pub fn erase_overlap_intervals(mut intervals: Vec>) -> i32 { if intervals.is_empty() { return 0; } @@ -441,7 +456,9 @@ impl Solution { } } ``` + ### C# + ```csharp public class Solution { @@ -463,9 +480,7 @@ public class Solution } ``` -

- From 49e386d20ba95edeffba686584a6b123597ddbba Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Thu, 18 Jan 2024 10:28:55 +0800 Subject: [PATCH 044/118] =?UTF-8?q?Update=201049.=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E4=B8=80=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84=E9=87=8D=E9=87=8F?= =?UTF-8?q?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/1049.最后一块石头的重量II.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index cc661317..4c3c01a0 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -472,6 +472,30 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int LastStoneWeightII(int[] stones) + { + int[] dp = new int[15001]; + int sum = 0; + foreach (int stone in stones) + { + sum += stone; + } + int target = sum / 2; + for (int i = 0; i < stones.Length; i++) + { + for (int j = target; j >= stones[i]; j--) + { + dp[j] = Math.Max(dp[j], dp[j - stones[i]] + stones[i]); + } + } + return sum - 2 * dp[target]; + } +} +```

From d8abbca4a877c4acd34744add2c69f940a4c5e38 Mon Sep 17 00:00:00 2001 From: qjd1774 Date: Thu, 18 Jan 2024 11:32:48 +0800 Subject: [PATCH 045/118] =?UTF-8?q?=E6=B7=BB=E5=8A=A0kama54.=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E6=95=B0=E5=AD=97.md=20Javascript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kama54.替换数字.md | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/kama54.替换数字.md b/problems/kama54.替换数字.md index 2b3d53de..130c42f7 100644 --- a/problems/kama54.替换数字.md +++ b/problems/kama54.替换数字.md @@ -245,7 +245,60 @@ class Solution: return ''.join(lst) ``` ### JavaScript: +```js +const readline = require("readline"); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}) + +function main() { + const num0 = "0".charCodeAt(); + const num9 = "9".charCodeAt(); + const a = "a".charCodeAt(); + const z = "z".charCodeAt(); + function isAZ(str) { + return str >= a && str <= z; + } + function isNumber(str) { + return str >= num0 && str <= num9; + } + rl.on("line", (input) => { + let n = 0; + for (let i = 0; i < input.length; i++) { + const val = input[i].charCodeAt(); + if (isNumber(val)) { + n+= 6; + } + if (isAZ(val)) { + n++; + } + } + const ans = new Array(n).fill(0); + let index = input.length - 1; + for (let i = n - 1; i >= 0; i--) { + const val = input[index].charCodeAt(); + if (isAZ(val)) { + ans[i] = input[index]; + } + if (isNumber(val)) { + ans[i] = "r"; + ans[i - 1] = "e"; + ans[i - 2] = "b"; + ans[i - 3] = "m"; + ans[i - 4] = "u"; + ans[i - 5] = "n"; + i -= 5; + } + index--; + } + console.log(ans.join("")); + }) +} + +main(); +``` ### TypeScript: From 017a4ce4ad985c09fe31a3d92d6cf0dab24e0bf9 Mon Sep 17 00:00:00 2001 From: WmW Date: Thu, 18 Jan 2024 14:20:40 +0800 Subject: [PATCH 046/118] =?UTF-8?q?update:=200435.=E6=97=A0=E9=87=8D?= =?UTF-8?q?=E5=8F=A0=E5=8C=BA=E9=97=B4=EF=BC=8Crust=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0435.无重叠区间.md | 188 +++++++++++++++++------------------- 1 file changed, 86 insertions(+), 102 deletions(-) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 0bfda5fc..cf9996dd 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -4,6 +4,7 @@

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

+ # 435. 无重叠区间 [力扣题目链接](https://leetcode.cn/problems/non-overlapping-intervals/) @@ -15,22 +16,19 @@ 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 示例 1: - -- 输入: [ [1,2], [2,3], [3,4], [1,3] ] -- 输出: 1 -- 解释: 移除 [1,3] 后,剩下的区间没有重叠。 +* 输入: [ [1,2], [2,3], [3,4], [1,3] ] +* 输出: 1 +* 解释: 移除 [1,3] 后,剩下的区间没有重叠。 示例 2: - -- 输入: [ [1,2], [1,2], [1,2] ] -- 输出: 2 -- 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 +* 输入: [ [1,2], [1,2], [1,2] ] +* 输出: 2 +* 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。 示例 3: - -- 输入: [ [1,2], [2,3] ] -- 输出: 0 -- 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 +* 输入: [ [1,2], [2,3] ] +* 输出: 0 +* 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。 ## 算法公开课 @@ -40,7 +38,7 @@ **相信很多同学看到这道题目都冥冥之中感觉要排序,但是究竟是按照右边界排序,还是按照左边界排序呢?** -其实都可以。主要就是为了让区间尽可能的重叠。 +其实都可以。主要就是为了让区间尽可能的重叠。 **我来按照右边界排序,从左向右记录非交叉区间的个数。最后用区间总数减去非交叉区间的个数就是需要移除的区间个数了**。 @@ -50,17 +48,17 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230201164134.png) -区间,1,2,3,4,5,6 都按照右边界排好序。 +区间,1,2,3,4,5,6都按照右边界排好序。 -当确定区间 1 和 区间 2 重叠后,如何确定是否与 区间 3 也重贴呢? +当确定区间 1 和 区间2 重叠后,如何确定是否与 区间3 也重贴呢? -就是取 区间 1 和 区间 2 右边界的最小值,因为这个最小值之前的部分一定是 区间 1 和区间 2 的重合部分,如果这个最小值也触达到区间 3,那么说明 区间 1,2,3 都是重合的。 +就是取 区间1 和 区间2 右边界的最小值,因为这个最小值之前的部分一定是 区间1 和区间2 的重合部分,如果这个最小值也触达到区间3,那么说明 区间 1,2,3都是重合的。 -接下来就是找大于区间 1 结束位置的区间,是从区间 4 开始。**那有同学问了为什么不从区间 5 开始?别忘了已经是按照右边界排序的了**。 +接下来就是找大于区间1结束位置的区间,是从区间4开始。**那有同学问了为什么不从区间5开始?别忘了已经是按照右边界排序的了**。 -区间 4 结束之后,再找到区间 6,所以一共记录非交叉区间的个数是三个。 +区间4结束之后,再找到区间6,所以一共记录非交叉区间的个数是三个。 -总共区间个数为 6,减去非交叉区间的个数 3。移除区间的最小数量就是 3。 +总共区间个数为6,减去非交叉区间的个数3。移除区间的最小数量就是3。 C++代码如下: @@ -86,9 +84,8 @@ public: } }; ``` - -- 时间复杂度:O(nlog n) ,有一个快排 -- 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要 n 次递归调用。因此确实需要 O(n)的栈空间 +* 时间复杂度:O(nlog n) ,有一个快排 +* 空间复杂度:O(n),有一个快排,最差情况(倒序)时,需要n次递归调用。因此确实需要O(n)的栈空间 大家此时会发现如此复杂的一个问题,代码实现却这么简单! @@ -96,11 +93,11 @@ public: ### 补充(1) -左边界排序可不可以呢? +左边界排序可不可以呢? -也是可以的,只不过 左边界排序我们就是直接求 重叠的区间,count 为记录重叠区间数。 +也是可以的,只不过 左边界排序我们就是直接求 重叠的区间,count为记录重叠区间数。 -```CPP +```CPP class Solution { public: static bool cmp (const vector& a, const vector& b) { @@ -111,9 +108,9 @@ public: sort(intervals.begin(), intervals.end(), cmp); int count = 0; // 注意这里从0开始,因为是记录重叠区间 int end = intervals[0][1]; // 记录区间分割点 - for (int i = 1; i < intervals.size(); i++) { + for (int i = 1; i < intervals.size(); i++) { if (intervals[i][0] >= end) end = intervals[i][1]; // 无重叠的情况 - else { // 重叠情况 + else { // 重叠情况 end = min(end, intervals[i][1]); count++; } @@ -123,9 +120,9 @@ public: }; ``` -其实代码还可以精简一下, 用 intervals[i][1] 替代 end 变量,只判断 重叠情况就好 +其实代码还可以精简一下, 用 intervals[i][1] 替代 end变量,只判断 重叠情况就好 -```CPP +```CPP class Solution { public: static bool cmp (const vector& a, const vector& b) { @@ -151,14 +148,14 @@ public: 本题其实和[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)非常像,弓箭的数量就相当于是非交叉区间的数量,只要把弓箭那道题目代码里射爆气球的判断条件加个等号(认为[0,1][1,2]不是相邻区间),然后用总区间数减去弓箭数量 就是要移除的区间数量了。 -把[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)代码稍做修改,就可以 AC 本题。 +把[452.用最少数量的箭引爆气球](https://programmercarl.com/0452.用最少数量的箭引爆气球.html)代码稍做修改,就可以AC本题。 ```CPP class Solution { public: // 按照区间右边界排序 static bool cmp (const vector& a, const vector& b) { - return a[1] < b[1]; // 右边界排序 + return a[1] < b[1]; // 右边界排序 } int eraseOverlapIntervals(vector>& intervals) { if (intervals.size() == 0) return 0; @@ -178,8 +175,7 @@ public: }; ``` -这里按照 左边界排序,或者按照右边界排序,都可以 AC,原理是一样的。 - +这里按照 左边界排序,或者按照右边界排序,都可以AC,原理是一样的。 ```CPP class Solution { public: @@ -208,8 +204,8 @@ public: ## 其他语言版本 -### Java +### Java ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -223,7 +219,7 @@ class Solution { continue; }else{ count++; - } + } } return intervals.length - count; } @@ -231,7 +227,6 @@ class Solution { ``` 按左边排序,不管右边顺序。相交的时候取最小的右边。 - ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -252,53 +247,47 @@ class Solution { } ``` -### Python - +### Python 贪心 基于左边界 - ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 - + intervals.sort(key=lambda x: x[0]) # 按照左边界升序排序 count = 0 # 记录重叠区间数量 - + for i in range(1, len(intervals)): if intervals[i][0] < intervals[i - 1][1]: # 存在重叠区间 intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]) # 更新重叠区间的右边界 count += 1 - + return count ``` - -贪心 基于左边界 把 452.用最少数量的箭引爆气球代码稍做修改 - +贪心 基于左边界 把452.用最少数量的箭引爆气球代码稍做修改 ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 - + intervals.sort(key=lambda x: x[0]) # 按照左边界升序排序 - + result = 1 # 不重叠区间数量,初始化为1,因为至少有一个不重叠的区间 - + for i in range(1, len(intervals)): if intervals[i][0] >= intervals[i - 1][1]: # 没有重叠 result += 1 else: # 重叠情况 intervals[i][1] = min(intervals[i - 1][1], intervals[i][1]) # 更新重叠区间的右边界 - + return len(intervals) - result ``` - -### Go - +### Go ```go func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -323,9 +312,7 @@ func min(a, b int) int { ``` ### Javascript - - 按右边界排序 - ```Javascript var eraseOverlapIntervals = function(intervals) { intervals.sort((a, b) => { @@ -342,29 +329,27 @@ var eraseOverlapIntervals = function(intervals) { count += 1 } } - + return intervals.length - count }; ``` - - 按左边界排序 - ```js -var eraseOverlapIntervals = function (intervals) { - // 按照左边界升序排列 - intervals.sort((a, b) => a[0] - b[0]); - let count = 1; - let end = intervals[intervals.length - 1][0]; - // 倒序遍历,对单个区间来说,左边界越大越好,因为给前面区间的空间越大 - for (let i = intervals.length - 2; i >= 0; i--) { - if (intervals[i][1] <= end) { - count++; - end = intervals[i][0]; +var eraseOverlapIntervals = function(intervals) { + // 按照左边界升序排列 + intervals.sort((a, b) => a[0] - b[0]) + let count = 1 + let end = intervals[intervals.length - 1][0] + // 倒序遍历,对单个区间来说,左边界越大越好,因为给前面区间的空间越大 + for(let i = intervals.length - 2; i >= 0; i--) { + if(intervals[i][1] <= end) { + count++ + end = intervals[i][0] + } } - } - // count 记录的是最大非重复区间的个数 - return intervals.length - count; -}; + // count 记录的是最大非重复区间的个数 + return intervals.length - count +} ``` ### TypeScript @@ -373,43 +358,43 @@ var eraseOverlapIntervals = function (intervals) { ```typescript function eraseOverlapIntervals(intervals: number[][]): number { - const length = intervals.length; - if (length === 0) return 0; - intervals.sort((a, b) => a[1] - b[1]); - let right: number = intervals[0][1]; - let count: number = 1; - for (let i = 1; i < length; i++) { - if (intervals[i][0] >= right) { - count++; - right = intervals[i][1]; + const length = intervals.length; + if (length === 0) return 0; + intervals.sort((a, b) => a[1] - b[1]); + let right: number = intervals[0][1]; + let count: number = 1; + for (let i = 1; i < length; i++) { + if (intervals[i][0] >= right) { + count++; + right = intervals[i][1]; + } } - } - return length - count; -} + return length - count; +}; ``` > 按左边界排序,从左往右遍历 ```typescript function eraseOverlapIntervals(intervals: number[][]): number { - if (intervals.length === 0) return 0; - intervals.sort((a, b) => a[0] - b[0]); - let right: number = intervals[0][1]; - let tempInterval: number[]; - let resCount: number = 0; - for (let i = 1, length = intervals.length; i < length; i++) { - tempInterval = intervals[i]; - if (tempInterval[0] >= right) { - // 未重叠 - right = tempInterval[1]; - } else { - // 有重叠,移除当前interval和前一个interval中右边界更大的那个 - right = Math.min(right, tempInterval[1]); - resCount++; + if (intervals.length === 0) return 0; + intervals.sort((a, b) => a[0] - b[0]); + let right: number = intervals[0][1]; + let tempInterval: number[]; + let resCount: number = 0; + for (let i = 1, length = intervals.length; i < length; i++) { + tempInterval = intervals[i]; + if (tempInterval[0] >= right) { + // 未重叠 + right = tempInterval[1]; + } else { + // 有重叠,移除当前interval和前一个interval中右边界更大的那个 + right = Math.min(right, tempInterval[1]); + resCount++; + } } - } - return resCount; -} + return resCount; +}; ``` ### Scala @@ -456,9 +441,7 @@ impl Solution { } } ``` - ### C# - ```csharp public class Solution { @@ -480,6 +463,7 @@ public class Solution } ``` +

From e0b0078eea56b6af0e18487e428fa78ff93313ec Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Fri, 19 Jan 2024 10:02:55 +0800 Subject: [PATCH 047/118] =?UTF-8?q?Update=200494.=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E5=92=8C=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/0494.目标和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 2d38b4d0..e7a05d45 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -585,6 +585,33 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int FindTargetSumWays(int[] nums, int target) + { + int sum = 0; + foreach (int num in nums) + { + sum += num; + } + if (Math.Abs(target) > sum) return 0; + if ((sum + target) % 2 == 1) return 0; + int bagSize = (sum + target) / 2; + int[] dp = new int[bagSize + 1]; + dp[0] = 1; + for (int i = 0; i < nums.Length; i++) + { + for (int j = bagSize; j >= nums[i]; j--) + { + dp[j] += dp[j - nums[i]]; + } + } + return dp[bagSize]; + } +} +```

From fddab1a7f4442e7cebf70f118b6157c6dfb3d67e Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sat, 20 Jan 2024 09:51:00 +0800 Subject: [PATCH 048/118] =?UTF-8?q?Update=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6=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/0474.一和零.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 8f6197ac..904d941e 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -533,6 +533,33 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int FindMaxForm(string[] strs, int m, int n) + { + int[,] dp = new int[m + 1, n + 1]; + foreach (string str in strs) + { + int zero = 0, one = 0; + foreach (char c in str) + { + if (c == '0') zero++; + else one++; + } + for (int i = m; i >= zero; i--) + { + for (int j = n; j >= one; j--) + { + dp[i, j] = Math.Max(dp[i, j], dp[i - zero, j - one] + 1); + } + } + } + return dp[m, n]; + } +} +```

From af4056827594bdc1db564a91cc86d196e5a48a6d Mon Sep 17 00:00:00 2001 From: EmmIons <48384706+EmmIons@users.noreply.github.com> Date: Sat, 20 Jan 2024 18:02:03 +0800 Subject: [PATCH 049/118] =?UTF-8?q?Update=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit java版本二维dp数组代码逻辑优化, 原版本的二维dp数组和一维dp数组的逻辑并不对应. --- problems/0518.零钱兑换II.md | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index 5c6efdcb..fa104541 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -224,20 +224,26 @@ class Solution { // 二维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; + int[][] dp = new int[coins.length][amount+1]; + + // 初始化边界值 + for(int i = 0; i < coins.length; i++){ + // 第一列的初始值为1 + dp[i][0] = 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]]; - } + for(int j = coins[0]; j <= amount; j++){ + // 初始化第一行 + dp[0][j] += dp[0][j-coins[0]]; + } + + for(int i = 1; i < coins.length; i++){ + for(int j = 1; j <= amount; j++){ + if(j < coins[i]) dp[i][j] = dp[i-1][j]; + else dp[i][j] = dp[i][j-coins[i]] + dp[i-1][j]; } } - return dp[coins.length - 1][amount]; + + return dp[coins.length-1][amount]; } } ``` From bcfa9202eba667e24df0512b842fa13669f36924 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Sun, 21 Jan 2024 10:29:39 +0800 Subject: [PATCH 050/118] =?UTF-8?q?Update=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A22=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/0518.零钱兑换II.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index 5c6efdcb..9fbe8ba3 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -347,6 +347,26 @@ object Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int Change(int amount, int[] coins) + { + int[] dp = new int[amount + 1]; + dp[0] = 1; + for (int i = 0; i < coins.Length; i++) + { + for (int j = coins[i]; j <= amount; j++) + { + if (j >= coins[i]) + dp[j] += dp[j - coins[i]]; + } + } + return dp[amount]; + } +} +```

From 68cdbdbb90f2d5a7a32278804f77663198e35a43 Mon Sep 17 00:00:00 2001 From: 0zz10 <56071597+0zz10@users.noreply.github.com> Date: Sun, 21 Jan 2024 15:40:51 -0800 Subject: [PATCH 051/118] =?UTF-8?q?Update=200503.=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit move second solution to 0496.下一个更大元素I --- problems/0503.下一个更大元素II.md | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index b788968c..6df83fb2 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -170,7 +170,6 @@ class Solution { ### Python: ```python -# 方法 1: class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: dp = [-1] * len(nums) @@ -181,26 +180,6 @@ class Solution: stack.pop() stack.append(i%len(nums)) return dp - -# 方法 2: -class Solution: - def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: - stack = [] - # 创建答案数组 - ans = [-1] * len(nums1) - for i in range(len(nums2)): - while len(stack) > 0 and nums2[i] > nums2[stack[-1]]: - # 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常 - if nums2[stack[-1]] in nums1: - # 锁定 num1 检索的 index - index = nums1.index(nums2[stack[-1]]) - # 更新答案数组 - ans[index] = nums2[i] - # 弹出小元素 - # 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了 - stack.pop() - stack.append(i) - return ans ``` ### Go: From 17a6cb3989befb0d6124f2854c17854dd46d62a1 Mon Sep 17 00:00:00 2001 From: 0zz10 <56071597+0zz10@users.noreply.github.com> Date: Sun, 21 Jan 2024 15:43:00 -0800 Subject: [PATCH 052/118] =?UTF-8?q?Update=200496.=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0I.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move solution from 0503.下一个更大元素II --- problems/0496.下一个更大元素I.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index 45797fb6..d97a3e84 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -256,6 +256,7 @@ class Solution { ### Python3 ```python +# 版本一 class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: result = [-1]*len(nums1) @@ -273,6 +274,26 @@ class Solution: stack.pop() stack.append(i) return result + +# 版本二 +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + # 创建答案数组 + ans = [-1] * len(nums1) + for i in range(len(nums2)): + while len(stack) > 0 and nums2[i] > nums2[stack[-1]]: + # 判断 num1 是否有 nums2[stack[-1]]。如果没有这个判断会出现指针异常 + if nums2[stack[-1]] in nums1: + # 锁定 num1 检索的 index + index = nums1.index(nums2[stack[-1]]) + # 更新答案数组 + ans[index] = nums2[i] + # 弹出小元素 + # 这个代码一定要放在 if 外面。否则单调栈的逻辑就不成立了 + stack.pop() + stack.append(i) + return ans ``` ### Go From 9eb2bec1b01e0baa9254401c732a6fb86d55df39 Mon Sep 17 00:00:00 2001 From: eeee0717 Date: Mon, 22 Jan 2024 10:32:00 +0800 Subject: [PATCH 053/118] =?UTF-8?q?Update=200377.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E7=BB=BC=E5=90=884=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/0377.组合总和Ⅳ.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index 05f852b1..a840ec9b 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -312,6 +312,28 @@ impl Solution { } } ``` +### C# +```csharp +public class Solution +{ + public int CombinationSum4(int[] nums, int target) + { + int[] dp = new int[target + 1]; + dp[0] = 1; + for (int i = 0; i <= target; i++) + { + for (int j = 0; j < nums.Length; j++) + { + if (i >= nums[j] && dp[i] < int.MaxValue - dp[i - nums[j]]) + { + dp[i] += dp[i - nums[j]]; + } + } + } + return dp[target]; + } +} +```

From d8f076ef514737ff4ad9247a7380ba2f7c8c7515 Mon Sep 17 00:00:00 2001 From: tlylt Date: Tue, 23 Jan 2024 07:41:36 +0800 Subject: [PATCH 054/118] Add two versions of intersection function in Go --- problems/0349.两个数组的交集.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 26a9286d..25c4e702 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -210,6 +210,8 @@ class Solution: ### Go: +(版本一)使用字典和集合 + ```go func intersection(nums1 []int, nums2 []int) []int { set:=make(map[int]struct{},0) // 用map模拟set @@ -230,6 +232,28 @@ func intersection(nums1 []int, nums2 []int) []int { } ``` +(版本二)使用数组 + +```go +func intersection(nums1 []int, nums2 []int) []int { + count1 := make([]int, 1001, 1001) + count2 := make([]int, 1001, 1001) + res := make([]int, 0) + for _, v := range nums1 { + count1[v] = 1 + } + for _, v := range nums2 { + count2[v] = 1 + } + for i := 0; i <= 1000; i++ { + if count1[i] + count2[i] == 2 { + res = append(res, i) + } + } + return res +} +``` + ### JavaScript: ```js From b0dbf080646b57157fa285559b748a2c8fc8a452 Mon Sep 17 00:00:00 2001 From: 0zz10 <56071597+0zz10@users.noreply.github.com> Date: Mon, 22 Jan 2024 20:45:36 -0800 Subject: [PATCH 055/118] =?UTF-8?q?Update=200127.=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8E=A5=E9=BE=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix syntax highlight --- problems/0127.单词接龙.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 97bc66d0..6f893310 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -198,7 +198,7 @@ class Solution { ### Python -``` +```python class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: wordSet = set(wordList) From e7e7c4665fe172bcaebed116bb16c3f39e0bc73c Mon Sep 17 00:00:00 2001 From: SteveL <66228787+stevenleon99@users.noreply.github.com> Date: Tue, 23 Jan 2024 21:51:52 -0500 Subject: [PATCH 056/118] =?UTF-8?q?Update=200059.=E8=9E=BA=E6=97=8B?= =?UTF-8?q?=E7=9F=A9=E9=98=B5II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit while (loop --) { i = startx; j = starty; // 下面开始的四个for就是模拟转了一圈 // 模拟填充上行从左到右(左闭右开) for (j; j < n - offset; j++) { res[i][j] = count++; } // 模拟填充右列从上到下(左闭右开) for (i; i < n - offset; i++) { res[i][j] = count++; } --- problems/0059.螺旋矩阵II.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 58378ffc..60281d48 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -87,11 +87,11 @@ public: // 下面开始的四个for就是模拟转了一圈 // 模拟填充上行从左到右(左闭右开) - for (j = starty; j < n - offset; j++) { - res[startx][j] = count++; + for (j; j < n - offset; j++) { + res[i][j] = count++; } // 模拟填充右列从上到下(左闭右开) - for (i = startx; i < n - offset; i++) { + for (i; i < n - offset; i++) { res[i][j] = count++; } // 模拟填充下行从右到左(左闭右开) From 671714fc4736f857977fdb355079bc1d7140ca44 Mon Sep 17 00:00:00 2001 From: Lina Date: Wed, 24 Jan 2024 21:23:21 +0000 Subject: [PATCH 057/118] =?UTF-8?q?=E6=8C=89=E7=85=A7=E8=A7=A3=E9=A2=98?= =?UTF-8?q?=E6=80=9D=E8=B7=AF=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81=E5=8F=8A?= =?UTF-8?q?=E5=8F=98=E9=87=8F=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 57 +++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 58378ffc..a34af5e3 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -138,42 +138,51 @@ public: ```Java class Solution { public int[][] generateMatrix(int n) { - int loop = 0; // 控制循环次数 - int[][] res = new int[n][n]; - int start = 0; // 每次循环的开始点(start, start) - int count = 1; // 定义填充数字 - int i, j; + int[][] nums = new int[n][n]; + int startX = 0, startY = 0; // 每一圈的起始点 + int offset = 1; + int count = 1; // 矩阵中需要填写的数字 + int loop = 1; // 记录当前的圈数 + int i, j; // j 代表列, i 代表行; - while (loop++ < n / 2) { // 判断边界后,loop从1开始 - // 模拟上侧从左到右 - for (j = start; j < n - loop; j++) { - res[start][j] = count++; + while (loop <= n / 2) { + + // 顶部 + // 左闭右开,所以判断循环结束时, j 不能等于 n - offset + for (j = startY; j < n - offset; j++) { + nums[startX][j] = count++; } - // 模拟右侧从上到下 - for (i = start; i < n - loop; i++) { - res[i][j] = count++; + // 右列 + // 左闭右开,所以判断循环结束时, i 不能等于 n - offset + for (i = startX; i < n - offset; i++) { + nums[i][j] = count++; } - // 模拟下侧从右到左 - for (; j >= loop; j--) { - res[i][j] = count++; + // 底部 + // 左闭右开,所以判断循环结束时, j != startY + for (; j > startY; j--) { + nums[i][j] = count++; } - // 模拟左侧从下到上 - for (; i >= loop; i--) { - res[i][j] = count++; + // 左列 + // 左闭右开,所以判断循环结束时, i != startX + for (; i > startX; i--) { + nums[i][j] = count++; } - start++; + startX++; + startY++; + offset++; + loop++; } - - if (n % 2 == 1) { - res[start][start] = count; + if (n % 2 == 1) { // n 为奇数时,单独处理矩阵中心的值 + nums[startX][startY] = count; } - - return res; + return nums; } } + + ``` ### python3: From e51ce46b75cae98e8b69bac491151f0a347d10e8 Mon Sep 17 00:00:00 2001 From: zhouzheng Date: Fri, 26 Jan 2024 11:18:54 +0800 Subject: [PATCH 058/118] =?UTF-8?q?update:=2070.=20=E7=88=AC=E6=A5=BC?= =?UTF-8?q?=E6=A2=AF=E8=BF=9B=E9=98=B6=E7=89=88=EF=BC=8C=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=20go=20=E8=AF=AD=E8=A8=80=E9=A2=98=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0070.爬楼梯完全背包版本.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index f8337cc0..4fa294cf 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -169,7 +169,32 @@ class climbStairs{ ### Go: +```go +func climbStairs(n int, m int) int { + dp := make([]int, n+1) + dp[0] = 1 + for i := 1; i <= n; i++ { + for j := 1; j <= m; j++ { + if i-j >= 0 { + dp[i] += dp[i-j] + } + } + } + return dp[n] +} +func main() { + // 读取输入n,m + reader := bufio.NewReader(os.Stdin) + input, _ := reader.ReadString('\n') + input = strings.TrimSpace(input) + nv := strings.Split(input, " ") + n, _ := strconv.Atoi(nv[0]) + m, _ := strconv.Atoi(nv[1]) + result := climbStairs(n, m) + fmt.Println(result) +} +``` ### JavaScript: From abc86e9a7d66851ada0e54f74efd50b9ce5da8f2 Mon Sep 17 00:00:00 2001 From: Heeqw <124508798+Heeqw@users.noreply.github.com> Date: Sat, 27 Jan 2024 17:05:04 +0800 Subject: [PATCH 059/118] =?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 增加了一种java语言的同步移动方法 --- problems/面试题02.07.链表相交.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index d0967b8b..e2905d49 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -105,6 +105,7 @@ public: ### Java: ```Java +(版本一)先行移动长链表实现同步移动 public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode curA = headA; @@ -149,6 +150,23 @@ public class Solution { } } + +(版本二) 合并链表实现同步移动 +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + // p1 指向 A 链表头结点,p2 指向 B 链表头结点 + ListNode p1 = headA, p2 = headB; + while (p1 != p2) { + // p1 走一步,如果走到 A 链表末尾,转到 B 链表 + if (p1 == null) p1 = headB; + else p1 = p1.next; + // p2 走一步,如果走到 B 链表末尾,转到 A 链表 + if (p2 == null) p2 = headA; + else p2 = p2.next; + } + return p1; + } +} ``` ### Python: From 8b35191534307420814a486d232b11027cc85504 Mon Sep 17 00:00:00 2001 From: qiuzidian <115708838+qiuzidian@users.noreply.github.com> Date: Mon, 29 Jan 2024 21:37:01 +0800 Subject: [PATCH 060/118] =?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 增加c语言版本解法 --- problems/0454.四数相加II.md | 70 +++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 1c262c87..3baeade5 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -412,6 +412,76 @@ public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { return res; } ``` +### C: + +```c +// 哈希表大小 +const int HASH_SIZE = 101; + +typedef struct node +{ + int val; + int count; + struct node *next; +}node, *HashMap; + +// 哈希表插入 +void hash_insert(HashMap hashmap[], int val){ + int idx = val < 0 ? (-val) % HASH_SIZE : val % HASH_SIZE, count = 0; + node *p = hashmap[idx]; + while (p->next != NULL) { + p = p->next; + if (p->val == val){ + (p->count)++; + return; + } + } + node *new = malloc(sizeof(node)); + new->val = val; + new->count = 1; + new->next = NULL; + p->next = new; + return; +} + +// 哈希表查找 +int hash_search(HashMap hashmap[], int val){ + int idx = val < 0 ? (-val) % HASH_SIZE : val % HASH_SIZE; + node *p = hashmap[idx]; + while (p->next != NULL){ + p = p->next; + if (p->val == val) return p->count; + } + return 0; +} + +int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums3, int nums3Size, int* nums4, int nums4Size){ + // 初始化哈希表 + HashMap hashmap[HASH_SIZE]; + for (int i = 0; i < HASH_SIZE; i++){ + hashmap[i] = malloc(sizeof(node)); + hashmap[i]->next = NULL; + } + + // 统计两个数组元素之和的负值和出现的次数,放到哈希表中 + int count = 0, num; + for (int i=0; i From 2f2e6856dbda03d1580b4301bf62dee04b0f641b Mon Sep 17 00:00:00 2001 From: qiuzidian <115708838+qiuzidian@users.noreply.github.com> Date: Mon, 29 Jan 2024 22:08:52 +0800 Subject: [PATCH 061/118] =?UTF-8?q?Update=200454.=E5=9B=9B=E6=95=B0?= =?UTF-8?q?=E7=9B=B8=E5=8A=A0II.md=EF=BC=8C=E8=A7=84=E8=8C=83=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0454.四数相加II.md | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 3baeade5..a0bf84da 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -418,20 +418,19 @@ public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { // 哈希表大小 const int HASH_SIZE = 101; -typedef struct node -{ +typedef struct node { int val; int count; struct node *next; -}node, *HashMap; +} node, *HashMap; // 哈希表插入 -void hash_insert(HashMap hashmap[], int val){ +void hash_insert(HashMap hashmap[], int val) { int idx = val < 0 ? (-val) % HASH_SIZE : val % HASH_SIZE, count = 0; node *p = hashmap[idx]; while (p->next != NULL) { p = p->next; - if (p->val == val){ + if (p->val == val) { (p->count)++; return; } @@ -445,10 +444,10 @@ void hash_insert(HashMap hashmap[], int val){ } // 哈希表查找 -int hash_search(HashMap hashmap[], int val){ +int hash_search(HashMap hashmap[], int val) { int idx = val < 0 ? (-val) % HASH_SIZE : val % HASH_SIZE; node *p = hashmap[idx]; - while (p->next != NULL){ + while (p->next != NULL) { p = p->next; if (p->val == val) return p->count; } @@ -458,23 +457,23 @@ int hash_search(HashMap hashmap[], int val){ int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums3, int nums3Size, int* nums4, int nums4Size){ // 初始化哈希表 HashMap hashmap[HASH_SIZE]; - for (int i = 0; i < HASH_SIZE; i++){ + for (int i = 0; i < HASH_SIZE; i++) { hashmap[i] = malloc(sizeof(node)); hashmap[i]->next = NULL; } // 统计两个数组元素之和的负值和出现的次数,放到哈希表中 int count = 0, num; - for (int i=0; i Date: Mon, 29 Jan 2024 22:18:50 +0800 Subject: [PATCH 062/118] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91?= =?UTF-8?q?=E4=BF=A1.md=EF=BC=8C=E6=B7=BB=E5=8A=A0c=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index b800c232..1dbf5de0 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -445,6 +445,25 @@ public bool CanConstruct(string ransomNote, string magazine) { return true; } +``` + +### C: + +```c +bool canConstruct(char* ransomNote, char* magazine) { + // 定义哈希映射数组 + int hashmap[26] = {0}; + // 对magazine中字符计数 + while (*magazine != '\0') hashmap[*magazine++ % 26]++; + // 遍历ransomNote,对应的字符自减,小于0说明该字符magazine没有或不足够表示 + while (*ransomNote != '\0') hashmap[*ransomNote++ % 26]--; + // 如果数组中存在负数,说明ransomNote不能由magazine里面的字符构成 + for (int i = 0; i < 26; i++) { + if (hashmap[i] < 0) return false; + } + return true; +} + ```

From 586b8efd38f2ee919c38b207d7fcb0a442def32c Mon Sep 17 00:00:00 2001 From: Heeqw <124508798+Heeqw@users.noreply.github.com> Date: Mon, 29 Jan 2024 23:39:32 +0800 Subject: [PATCH 063/118] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加java语言版本的双指针法 --- problems/0001.两数之和.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 1785fe5f..80218cb5 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -133,6 +133,7 @@ public: ### Java: ```java +//使用哈希表 public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if(nums == null || nums.length == 0){ @@ -151,6 +152,43 @@ public int[] twoSum(int[] nums, int target) { return res; } ``` +```java +//使用双指针 +public int[] twoSum(int[] nums, int target) { + int m=0,n=0,k,board=0; + int[] res=new int[2]; + int[] tmp1=new int[nums.length]; + //备份原本下标的nums数组 + System.arraycopy(nums,0,tmp1,0,nums.length); + //将nums排序 + Arrays.sort(nums); + //双指针 + for(int i=0,j=nums.length-1;itarget) + j--; + else if(nums[i]+nums[j]==target){ + m=i; + n=j; + break; + } + } + //找到nums[m]在tmp1数组中的下标 + for(k=0;k Date: Mon, 29 Jan 2024 13:42:49 -0800 Subject: [PATCH 064/118] fix: Correct function type --- problems/0235.二叉搜索树的最近公共祖先.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b691a45a..2a11f9f4 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -298,7 +298,7 @@ class Solution: return self.traversal(root, p, q) ``` -迭代法(版本二)精简 +递归法(版本二)精简 ```python class Solution: def lowestCommonAncestor(self, root, p, q): From 1bd8143bb241fbe0b1ce998e740902da5bfe839e Mon Sep 17 00:00:00 2001 From: Heeqw <124508798+Heeqw@users.noreply.github.com> Date: Tue, 30 Jan 2024 16:27:08 +0800 Subject: [PATCH 065/118] =?UTF-8?q?Update=200015.=E4=B8=89=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加了java语言版本的哈希解法 --- problems/0015.三数之和.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 91fc9d68..bf165788 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -256,7 +256,7 @@ while (right > left) { ## 其他语言版本 ### Java: - +(版本一) 双指针 ```Java class Solution { public List> threeSum(int[] nums) { @@ -297,7 +297,43 @@ class Solution { } } ``` +(版本二) 使用哈希集合 +```Java +class Solution { + public List> threeSum(int[] nums) { + List> result = new ArrayList<>(); + Arrays.sort(nums); + for (int i = 0; i < nums.length; i++) { + // 如果第一个元素大于零,不可能凑成三元组 + if (nums[i] > 0) { + return result; + } + // 三元组元素a去重 + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + + HashSet set = new HashSet<>(); + for (int j = i + 1; j < nums.length; j++) { + // 三元组元素b去重 + if (j > i + 2 && nums[j] == nums[j - 1] && nums[j - 1] == nums[j - 2]) { + continue; + } + + int c = -nums[i] - nums[j]; + if (set.contains(c)) { + result.add(Arrays.asList(nums[i], nums[j], c)); + set.remove(c); // 三元组元素c去重 + } else { + set.add(nums[j]); + } + } + } + return result; + } +} +``` ### Python: (版本一) 双指针 From 51481e11f50bb4596c15cc719313d43686a0987d Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Fri, 2 Feb 2024 11:06:31 +0800 Subject: [PATCH 066/118] =?UTF-8?q?Update=200090.=E5=AD=90=E9=9B=86II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这里与“补充”部分重复了,建议删掉 --- problems/0090.子集II.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 1bb63a34..6d618978 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -158,13 +158,6 @@ public: 其实这道题目的知识点,我们之前都讲过了,如果之前讲过的子集问题和去重问题都掌握的好,这道题目应该分分钟AC。 -当然本题去重的逻辑,也可以这么写 - -```cpp -if (i > startIndex && nums[i] == nums[i - 1] ) { - continue; -} -``` ## 其他语言版本 From e9a0259345d77c9b9d9e27132040da858d238f44 Mon Sep 17 00:00:00 2001 From: BanTanger <1290288968@qq.com> Date: Mon, 5 Feb 2024 12:28:07 +0800 Subject: [PATCH 067/118] =?UTF-8?q?=E7=AE=80=E5=8C=96=E5=88=86=E6=94=AF?= =?UTF-8?q?=E9=80=BB=E8=BE=91=EF=BC=8C=E5=A6=82=E6=9E=9C=E7=94=A8=E4=BA=86?= =?UTF-8?q?=20return=20=E5=B0=B1=E4=B8=8D=E7=94=A8=20if=20else=20=E6=8E=A7?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0968.监控二叉树.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 305f3ae5..9743ca2b 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -369,8 +369,44 @@ class Solution { } ``` +简化分支版本: + +```java +class Solution { + static int ans; + public int minCameraCover(TreeNode root) { + ans = 0; // 初始化 + if(f(root) == 0) ans ++; + return ans; + } + // 定义 f 函数有三种返回值情况 + // 0:表示 x 节点没有被相机监控,只能依靠父节点放相机 + // 1:表示 x 节点被相机监控,但相机不是放在自身节点上 + // 2:表示 x 节点被相机监控,但相机放在自身节点上 + public static int f(TreeNode x) { + if(x == null) return 1; // 空树认为被监控,但没有相机 + // 左右递归到最深处 + int l = f(x.left); + int r = f(x.right); + // 有任意一个子节点为空,就需要当前节点放相机,不然以后没机会 + if(l == 0 || r == 0) { + ans ++; // 放相机 + return 2; + } + // 贪心策略,左右子树都被监控,且没有监控到当前节点, + // 那么最有利的情况就是将相机放置在当前节点父节点上, + // 因为这样能多监控可能的子树节点和父父节点 + if(l == 1 && r == 1) return 0; + // 剩下情况就是左右子树有可能为 2,即当前节点被监控 + return 1; + } +} +``` + + ### Python + 贪心(版本一) ```python class Solution: @@ -757,4 +793,3 @@ public class Solution - From f618d35d8e39830d643177eda182944741427a6f Mon Sep 17 00:00:00 2001 From: Daixing Zhou <43519171+zhoudaixing@users.noreply.github.com> Date: Mon, 5 Feb 2024 15:59:20 +0800 Subject: [PATCH 068/118] =?UTF-8?q?=E5=A2=9E=E5=8A=A00347=E5=89=8DK?= =?UTF-8?q?=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0=E7=9A=84JavaScrip?= =?UTF-8?q?t=E4=BD=BF=E7=94=A8=E4=BC=98=E5=85=88=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=BA=93=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 94b29eba..93d605f5 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -324,6 +324,34 @@ func topKFrequent(nums []int, k int) []int { ### JavaScript: +解法一: +Leetcode 提供了优先队列的库,具体文档可以参见 [@datastructures-js/priority-queue](https://github.com/datastructures-js/priority-queue/blob/v5/README.md)。 + +```js +var topKFrequent = function (nums, k) { + const map = new Map(); + const res = []; + //使用 map 统计元素出现频率 + for (const num of nums) { + map.set(num, (map.get(num) || 0) + 1); + } + //创建小顶堆 + const heap = new PriorityQueue({ + compare: (a, b) => a.value - b.value + }) + for (const [key, value] of map) { + heap.enqueue({ key, value }); + if (heap.size() > k) heap.dequeue(); + } + //处理输出 + while (heap.size()) res.push(heap.dequeue().key); + return res; +}; +``` + +解法二: +手写实现优先队列 + ```js // js 没有堆 需要自己构造 class Heap { From 3d90f1ed267ebc68f523c8221677115f74aa8912 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Mon, 5 Feb 2024 16:31:15 +0800 Subject: [PATCH 069/118] =?UTF-8?q?Update=2020201126=E8=B4=AA=E5=BF=83?= =?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/周总结/20201126贪心周末总结.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/周总结/20201126贪心周末总结.md b/problems/周总结/20201126贪心周末总结.md index cdfe4a96..3494a320 100644 --- a/problems/周总结/20201126贪心周末总结.md +++ b/problems/周总结/20201126贪心周末总结.md @@ -69,7 +69,7 @@ 代码很简单,但是思路却比较难。还需要反复琢磨。 针对[贪心算法:最大子序和](https://programmercarl.com/0053.最大子序和.html)文章中给出的贪心代码如下; -``` +```cpp class Solution { public: int maxSubArray(vector& nums) { From c2cf9f854182541e915a94619fc8cba0b48445d1 Mon Sep 17 00:00:00 2001 From: Ryanhuang88 <145511591+Ryanhuang88@users.noreply.github.com> Date: Tue, 13 Feb 2024 22:02:49 -0500 Subject: [PATCH 070/118] Update join.md --- problems/qita/join.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/qita/join.md b/problems/qita/join.md index a2698e66..62dec674 100644 --- a/problems/qita/join.md +++ b/problems/qita/join.md @@ -111,7 +111,7 @@ python代码 有的录友是一个pull request 里有很多commit (一个commit是一道题目的代码)。 -有的录友是一个pull request 里有有一个commit。 +有的录友是一个pull request 里只有一个commit。

From 64edc63251e8862fc98cfe9635f360cccada4ceb Mon Sep 17 00:00:00 2001 From: Ryanhuang88 <145511591+Ryanhuang88@users.noreply.github.com> Date: Tue, 13 Feb 2024 22:07:05 -0500 Subject: [PATCH 071/118] =?UTF-8?q?Update=200685.=E5=86=97=E4=BD=99?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0685.冗余连接II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0685.冗余连接II.md b/problems/0685.冗余连接II.md index 31b2ad24..0cad5ad5 100644 --- a/problems/0685.冗余连接II.md +++ b/problems/0685.冗余连接II.md @@ -81,7 +81,7 @@ for (int i = 0; i < n; i++) { } ``` -前两种入度为2的情况,一定是删除指向入度为2的节点的两条边其中的一条,如果删了一条,判断这个图是一个树,那么这条边就是答案,同时注意要从后向前遍历,因为如果两天边删哪一条都可以成为树,就删最后那一条。 +前两种入度为2的情况,一定是删除指向入度为2的节点的两条边其中的一条,如果删了一条,判断这个图是一个树,那么这条边就是答案,同时注意要从后向前遍历,因为如果两条边删哪一条都可以成为树,就删最后那一条。 代码如下: From e8e2f249632170cbd25ef874e9875c84784d1440 Mon Sep 17 00:00:00 2001 From: anini <1660470561@qq.com> Date: Sat, 17 Feb 2024 12:42:10 +0800 Subject: [PATCH 072/118] =?UTF-8?q?Update=201002.=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6.md=20=E6=9B=B4=E6=96=B0Go?= =?UTF-8?q?=E7=89=88=E6=9C=AC-=E6=9B=B4=E6=96=B0=E4=B8=BA=E4=B8=8EC++?= =?UTF-8?q?=E7=9B=B8=E5=90=8C=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/.gitignore | 8 +++++ problems/1002.查找常用字符.md | 68 +++++++++++++++++++---------------- 2 files changed, 46 insertions(+), 30 deletions(-) create mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 57fa7dae..8d81e3f8 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -327,37 +327,45 @@ var commonChars = function(words) { ### GO ```golang -func commonChars(words []string) []string { - length:=len(words) - fre:=make([][]int,0)//统计每个字符串的词频 - res:=make([]string,0) - //统计词频 - for i:=0;i 0 { + s := string('a' + i) // rune -> string + result = append(result, s) + hash[i]-- + } + } + + return result } -func min(a,b int)int{ - if a>b{ - return b - } - return a + +func min(a, b int) int { + if a < b { + return a + } + return b } ``` From df8878b79192527f3d8617e09c93227340d03c10 Mon Sep 17 00:00:00 2001 From: gdstzmy <79707886+gdstzmy@users.noreply.github.com> Date: Tue, 20 Feb 2024 18:09:07 +0800 Subject: [PATCH 073/118] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加go语言贪心法 --- problems/0053.最大子序和.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 78c8b382..74ff2ca4 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -230,7 +230,25 @@ class Solution: ``` ### Go +贪心法 +```go +func maxSubArray(nums []int) int { + max := nums[0] + count := 0 + for i := 0; i < len(nums); i++{ + count += nums[i] + if count > max{ + max = count + } + if count < 0 { + count = 0 + } + } + return max +} +``` +动态规划 ```go func maxSubArray(nums []int) int { maxSum := nums[0] From 13edf8d8aa64be5d4e34d64186098c734ba71035 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Thu, 22 Feb 2024 14:40:15 +0800 Subject: [PATCH 074/118] Delete .idea/.gitignore --- .idea/.gitignore | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b81..00000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml From 2c160f31c511429053e33f9c8216e49d90b98360 Mon Sep 17 00:00:00 2001 From: zhaohanyan Date: Thu, 22 Feb 2024 12:05:47 -0500 Subject: [PATCH 075/118] =?UTF-8?q?Update=20kama55.=E5=8F=B3=E6=97=8B?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加python解法,已在kama上测试通过 --- problems/kama55.右旋字符串.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/problems/kama55.右旋字符串.md b/problems/kama55.右旋字符串.md index 17c97eaa..38e37322 100644 --- a/problems/kama55.右旋字符串.md +++ b/problems/kama55.右旋字符串.md @@ -211,7 +211,17 @@ public class Main { ``` ### Python: +```Python +#注意:python中字符串是不可变的,所以使用python一定要创建新的字符串 +#获取输入的数字k和字符串 +k = int(input()) +s = input() + +#通过切片反转第一段和第二段字符串 +s = s[len(s)-k:] + s[:len(s)-k] +print(s) +``` ### Go: ```go From c4ad2ec22e01bc0cdfde6dbbea91748e20bbdf16 Mon Sep 17 00:00:00 2001 From: zhaohanyan Date: Thu, 22 Feb 2024 12:10:18 -0500 Subject: [PATCH 076/118] =?UTF-8?q?Update=20kama55.=E5=8F=B3=E6=97=8B?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 注解更清晰 --- problems/kama55.右旋字符串.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/kama55.右旋字符串.md b/problems/kama55.右旋字符串.md index 38e37322..71371860 100644 --- a/problems/kama55.右旋字符串.md +++ b/problems/kama55.右旋字符串.md @@ -212,13 +212,12 @@ public class Main { ### Python: ```Python -#注意:python中字符串是不可变的,所以使用python一定要创建新的字符串 - #获取输入的数字k和字符串 k = int(input()) s = input() #通过切片反转第一段和第二段字符串 +#注意:python中字符串是不可变的,所以也需要额外空间 s = s[len(s)-k:] + s[:len(s)-k] print(s) ``` From a45fd00a27d03000eb3b327d94abd007ee0ae305 Mon Sep 17 00:00:00 2001 From: lhp <932606153@qq.com> Date: Fri, 23 Feb 2024 10:54:04 +0800 Subject: [PATCH 077/118] =?UTF-8?q?0827:=E6=9C=80=E5=A4=A7=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E5=B2=9B----=E6=B7=BB=E5=8A=A0js=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0827.最大人工岛.md | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0827.最大人工岛.md b/problems/0827.最大人工岛.md index 4feb78de..3f32dd7a 100644 --- a/problems/0827.最大人工岛.md +++ b/problems/0827.最大人工岛.md @@ -348,6 +348,71 @@ class Solution: ``` +### JavaScript + +```JavaScript + +var largestIsland = function(grid) { +let res = 0; +const m = grid.length; +const n = grid[0].length; +const tag = new Array(n).fill().map(_ => new Array(m).fill(0)); +const area = new Map(); +const dir = [[0,1],[0,-1],[1,0],[-1,0]]; +const dfs = (grid,tag,x,y,mark) => { + let res = 1; + tag[x][y] = mark; + for(let i = 0; i < dir.length; i++) { + let nextX = x + dir[i][0]; + let nextY = y + dir[i][1]; + if(nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) { + continue; + } + if(grid[nextX][nextY] === 1 && tag[nextX][nextY] === 0) { + res += dfs(grid,tag,nextX,nextY,mark); + } + } + return res; +} +let mark = 2; +//将岛屿用mark标记 +for(let i = 0; i < m; i++) { + for(let j = 0; j < n; j++) { + if(grid[i][j] === 1 && tag[i][j] === 0) { + area.set(mark,dfs(grid,tag,i,j,mark)); + res = Math.max(res,area.get(mark)); + mark++; + } + } +} +//将一个非岛屿格子变为岛屿 +for(let i = 0; i < m; i++) { + for(let j = 0; j < n; j++) { + if(grid[i][j] === 0) { + let z = 1; + const connected = new Set(); + for(let k = 0; k < dir.length; k++) { + let nextX = i + dir[k][0]; + let nextY = j + dir[k][1]; + if(nextX < 0 || nextX >= m || nextY < 0 || nextY >= n || tag[nextX][nextY] === 0 || connected.has(tag[nextX][nextY])) { + continue; + } + z += area.get(tag[nextX][nextY]); + connected.add(tag[nextX][nextY]); + } + res = Math.max(res,z); + } + } +} +return res; +}; + + +``` + + + +

From ea13bb2d2ef23790fa775386537692650b3cbc6c Mon Sep 17 00:00:00 2001 From: "435962415@qq.com" Date: Fri, 23 Feb 2024 12:00:50 +0800 Subject: [PATCH 078/118] =?UTF-8?q?=C2=96827.=E6=9C=80=E5=A4=A7=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E5=B2=9B=20=E6=B7=BB=E5=8A=A0go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0827.最大人工岛.md | 91 +++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/problems/0827.最大人工岛.md b/problems/0827.最大人工岛.md index 4feb78de..cac67676 100644 --- a/problems/0827.最大人工岛.md +++ b/problems/0827.最大人工岛.md @@ -346,6 +346,97 @@ class Solution: return res +``` + +### Go + +```go +func largestIsland(grid [][]int) int { + dir := [][]int{{0, 1}, {1, 0}, {-1, 0}, {0, -1}} + n := len(grid) + m := len(grid[0]) + area := 0 + visited := make([][]bool, n) + for i := 0; i < n; i++ { + visited[i] = make([]bool, m) + } + gridNum := make(map[int]int, 0) // 记录每一个岛屿的面积 + mark := 2 // 记录每个岛屿的编号 + isAllGrid := true + res := 0 // 标记是否整个地图都是陆地 + + var dfs func(grid [][]int, visited [][]bool, x, y, mark int) + dfs = func(grid [][]int, visited [][]bool, x, y, mark int) { + // 终止条件:访问过的节点 或者 遇到海水 + if visited[x][y] || grid[x][y] == 0 { + return + } + visited[x][y] = true // 标记访问过 + grid[x][y] = mark // 给陆地标记新标签 + area++ + for i := 0; i < 4; i++ { + nextX := x + dir[i][0] + nextY := y + dir[i][1] + if nextX < 0 || nextX >= len(grid) || nextY < 0 || nextY >= len(grid[0]) { + continue + } + dfs(grid, visited, nextX, nextY, mark) + } + } + + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + if grid[i][j] == 0 { + isAllGrid = false + } + if !visited[i][j] && grid[i][j] == 1 { + area = 0 + dfs(grid, visited, i, j, mark) // 将与其链接的陆地都标记上 true + gridNum[mark] = area // 记录每一个岛屿的面积 + mark++ // 更新下一个岛屿编号 + } + } + } + if isAllGrid { + return n * m + } + // 根据添加陆地的位置,计算周边岛屿面积之和 + visitedGrid := make(map[int]struct{}) // 标记访问过的岛屿 + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + count := 1 // 记录连接之后的岛屿数量 + visitedGrid = make(map[int]struct{}) // 每次使用时,清空 + if grid[i][j] == 0 { + for k := 0; k < 4; k++ { + // 计算相邻坐标 + nearI := i + dir[k][0] + nearJ := j + dir[k][1] + if nearI < 0 || nearI >= len(grid) || nearJ < 0 || nearJ >= len(grid[0]) { + continue + } + // 添加过的岛屿不要重复添加 + if _, ok := visitedGrid[grid[nearI][nearJ]]; ok { + continue + } + // 把相邻四面的岛屿数量加起来 + count += gridNum[grid[nearI][nearJ]] + // 标记该岛屿已经添加过 + visitedGrid[grid[nearI][nearJ]] = struct{}{} + } + } + res = max827(res, count) + } + } + return res +} + +func max827(x, y int) int { + if x > y { + return x + } + return y +} + ```

From b4f55e72745f4f6fbf27dd4bdb2201f1b430b9f2 Mon Sep 17 00:00:00 2001 From: zhangchang Date: Sat, 24 Feb 2024 22:46:14 +0800 Subject: [PATCH 079/118] =?UTF-8?q?=E4=BC=98=E5=8C=96Python=E9=80=92?= =?UTF-8?q?=E5=BD=92=E6=97=B6=E6=89=80=E9=9C=80=E8=A6=81=E7=9A=84=E5=86=85?= =?UTF-8?q?=E5=AD=98=E5=BC=80=E9=94=80=E5=92=8C=E6=97=B6=E9=97=B4=E6=B6=88?= =?UTF-8?q?=E8=80=97=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 54 ++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index edd55aad..4621d4a7 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -180,26 +180,34 @@ class Solution { class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: - if not root: - return [] - - left = self.preorderTraversal(root.left) - right = self.preorderTraversal(root.right) - - return [root.val] + left + right + res = [] + + def dfs(node): + if node is None: + return + + res.append(node.val) + dfs(node.left) + dfs(node.right) + + return res ``` ```python # 中序遍历-递归-LC94_二叉树的中序遍历 class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: - if root is None: - return [] - - left = self.inorderTraversal(root.left) - right = self.inorderTraversal(root.right) - - return left + [root.val] + right + res = [] + + def dfs(node): + if node is None: + return + + dfs(node.left) + res.append(node.val) + dfs(node.right) + + return res ``` ```python @@ -207,13 +215,17 @@ class Solution: # 后序遍历-递归-LC145_二叉树的后序遍历 class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: - if not root: - return [] - - left = self.postorderTraversal(root.left) - right = self.postorderTraversal(root.right) - - return left + right + [root.val] + res = [] + + def dfs(node): + if node is None: + return + + dfs(node.left) + dfs(node.right) + res.append(node.val) + + return res ``` ### Go: From f5fc6baddca9af176b77648229ae26fd4bae137e Mon Sep 17 00:00:00 2001 From: meifannao Date: Sun, 25 Feb 2024 22:12:35 +0800 Subject: [PATCH 080/118] =?UTF-8?q?0647.=E5=9B=9E=E6=96=87=E5=AD=90?= =?UTF-8?q?=E4=B8=B2=E6=B7=BB=E5=8A=A0Golang=E7=9A=84=E5=8F=8C=E6=8C=87?= =?UTF-8?q?=E9=92=88=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index d94d18c5..4887ff83 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -397,6 +397,7 @@ class Solution: ``` ### Go: +> 动态规划: ```Go func countSubstrings(s string) int { @@ -422,6 +423,47 @@ func countSubstrings(s string) int { return res } ``` +> 动态规划:简洁版 +```Go +func countSubstrings(s string) int { + res := 0 + dp := make([][]bool, len(s)) + for i := 0; i < len(s); i++ { + dp[i] = make([]bool, len(s)) + } + + for i := len(s) - 1; i >= 0; i-- { + for j := i; j < len(s); j++ { + if s[i] == s[j] && (j-i <= 1 || dp[i+1][j-1]) { + res++ + dp[i][j] = true + } + } + } + return res +} +``` + +> 双指针法: +```Go +func countSubstrings(s string) int { + extend := func(i, j int) int { + res := 0 + for i >= 0 && j < len(s) && s[i] == s[j] { + i -- + j ++ + res ++ + } + return res + } + res := 0 + for i := 0; i < len(s); i++ { + res += extend(i, i) // 以i为中心 + res += extend(i, i+1) // 以i和i+1为中心 + } + return res +} +``` ### Javascript: From 9c5b5676ee221d11280f66b1456ae82822154871 Mon Sep 17 00:00:00 2001 From: Han <90488412+HanCai98@users.noreply.github.com> Date: Sun, 25 Feb 2024 22:48:39 -0500 Subject: [PATCH 081/118] =?UTF-8?q?correct=20typo=20in=200200.=E5=B2=9B?= =?UTF-8?q?=E5=B1=BF=E6=95=B0=E9=87=8F.=E6=B7=B1=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 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0200.岛屿数量.深搜版.md b/problems/0200.岛屿数量.深搜版.md index 18442943..83d295bd 100644 --- a/problems/0200.岛屿数量.深搜版.md +++ b/problems/0200.岛屿数量.深搜版.md @@ -37,7 +37,7 @@ 在遇到标记过的陆地节点和海洋节点的时候直接跳过。 这样计数器就是最终岛屿的数量。 -那么如果把节点陆地所能遍历到的陆地都标记上呢,就可以使用 DFS,BFS或者并查集。 +那么如何把节点陆地所能遍历到的陆地都标记上呢,就可以使用 DFS,BFS或者并查集。 ### 深度优先搜索 From 415b031025b725cf7ccd109b16716920afb7ccc6 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Mon, 26 Feb 2024 20:47:23 +0800 Subject: [PATCH 082/118] =?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 0045.跳跃游戏||新增C语言实现 --- problems/0045.跳跃游戏II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index d290f55e..c6433ea8 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -492,7 +492,34 @@ impl Solution { } } ``` +### C + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int jump(int* nums, int numsSize) { + if(numsSize == 1){ + return 0; + } + int count = 0; + // 记录当前能走的最远距离 + int curDistance = 0; + // 记录下一步能走的最远距离 + int nextDistance = 0; + for(int i = 0; i < numsSize; i++){ + nextDistance = max(i + nums[i], nextDistance); + // 下标到了当前的最大距离 + if(i == nextDistance){ + count++; + curDistance = nextDistance; + } + } + return count; +} +``` + ### C# + ```csharp // 版本二 public class Solution @@ -518,3 +545,4 @@ public class Solution + From 3fc2fb99545d84f7965bec15e14ac7ae98754c94 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:03:50 +0800 Subject: [PATCH 083/118] =?UTF-8?q?Update=20=E5=9B=BE=E8=AE=BA=E5=B9=B6?= =?UTF-8?q?=E6=9F=A5=E9=9B=86=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正错别字和语病 --- problems/图论并查集理论基础.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/图论并查集理论基础.md b/problems/图论并查集理论基础.md index 347bf58f..a65d4807 100644 --- a/problems/图论并查集理论基础.md +++ b/problems/图论并查集理论基础.md @@ -108,7 +108,7 @@ bool isSame(int u, int v) { ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230602102619.png) -如果这棵多叉树高度很深的话,每次find函数 去寻找跟的过程就要递归很多次。 +如果这棵多叉树高度很深的话,每次find函数 去寻找根的过程就要递归很多次。 我们的目的只需要知道这些节点在同一个根下就可以,所以对这棵多叉树的构造只需要这样就可以了,如图: @@ -300,7 +300,7 @@ join(3, 2); **因为路经压缩了** -即如下代码在寻找跟的过程中,会有路径压缩,减少 下次查询的路径长度。 +即如下代码在寻找根的过程中,会有路径压缩,减少 下次查询的路径长度。 ``` // 并查集里寻根的过程 @@ -396,7 +396,7 @@ void join(int u, int v) { if (rank[u] <= rank[v]) father[u] = v; // rank小的树合入到rank大的树 else father[v] = u; - if (rank[u] == rank[v] && u != v) rank[v]++; // 如果两棵树高度相同,则v的高度+1因为,方面 if (rank[u] <= rank[v]) father[u] = v; 注意是 <= + if (rank[u] == rank[v] && u != v) rank[v]++; // 如果两棵树高度相同,则v的高度+1因为,上面 if (rank[u] <= rank[v]) father[u] = v; 注意是 <= } ``` @@ -423,7 +423,7 @@ void join(int u, int v) { 空间复杂度: O(n) ,申请一个father数组。 -关于时间复杂度,如果想精确表达出来需要繁琐的数学证明,就不在本篇讲解范围内了,大家感兴趣可以自己去深入去研究。 +关于时间复杂度,如果想精确表达出来需要繁琐的数学证明,就不在本篇讲解范围内了,大家感兴趣可以自己去深入研究。 这里做一个简单的分析思路。 From 94e50d08b9be536ade4694b78c2310bfbd43f128 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:36:59 +0800 Subject: [PATCH 084/118] =?UTF-8?q?Update=200685.=E5=86=97=E4=BD=99?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加cpp代码高亮 --- problems/0685.冗余连接II.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0685.冗余连接II.md b/problems/0685.冗余连接II.md index 0cad5ad5..c07dda3a 100644 --- a/problems/0685.冗余连接II.md +++ b/problems/0685.冗余连接II.md @@ -69,7 +69,7 @@ edges[2][0] = 2,edges[2][1] = 3, 搞清楚之后,我们如何统计入度呢? -即 edges[i][1] 表示的节点都是 箭头指向的节点,即这个几点有一个入度! (如果想统计出度,那么就是 edges[i][0])。 +即 edges[i][1] 表示的节点都是 箭头指向的节点,即这个节点有一个入度! (如果想统计出度,那么就是 edges[i][0])。 所以,统计入度的代码如下: @@ -108,7 +108,7 @@ if (vec.size() > 0) { 可以定义一个函数,代码如下: -``` +```cpp // 在有向图里找到删除的那条边,使其变成树,返回值就是要删除的边 vector getRemoveEdge(const vector>& edges) ``` From c88104b1af80e11ce78ff84147016421b905910c Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 20:25:03 +0800 Subject: [PATCH 085/118] =?UTF-8?q?Update=200669.=E4=BF=AE=E5=89=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加代码高亮 --- problems/0669.修剪二叉搜索树.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 916013c5..6824c7e2 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -79,7 +79,7 @@ public: 代码如下: -``` +```cpp TreeNode* trimBST(TreeNode* root, int low, int high) ``` @@ -87,7 +87,7 @@ TreeNode* trimBST(TreeNode* root, int low, int high) 修剪的操作并不是在终止条件上进行的,所以就是遇到空节点返回就可以了。 -``` +```cpp if (root == nullptr ) return nullptr; ``` @@ -97,7 +97,7 @@ if (root == nullptr ) return nullptr; 代码如下: -``` +```cpp if (root->val < low) { TreeNode* right = trimBST(root->right, low, high); // 寻找符合区间[low, high]的节点 return right; @@ -108,7 +108,7 @@ if (root->val < low) { 代码如下: -``` +```cpp if (root->val > high) { TreeNode* left = trimBST(root->left, low, high); // 寻找符合区间[low, high]的节点 return left; @@ -119,7 +119,7 @@ if (root->val > high) { 最后返回root节点,代码如下: -``` +```cpp root->left = trimBST(root->left, low, high); // root->left接入符合条件的左孩子 root->right = trimBST(root->right, low, high); // root->right接入符合条件的右孩子 return root; @@ -133,7 +133,7 @@ return root; 如下代码相当于把节点0的右孩子(节点2)返回给上一层, -``` +```cpp if (root->val < low) { TreeNode* right = trimBST(root->right, low, high); // 寻找符合区间[low, high]的节点 return right; @@ -142,7 +142,7 @@ if (root->val < low) { 然后如下代码相当于用节点3的左孩子 把下一层返回的 节点0的右孩子(节点2) 接住。 -``` +``` cpp root->left = trimBST(root->left, low, high); ``` From a518db03dd3265f53d98d2277f5da12323363958 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 20:26:06 +0800 Subject: [PATCH 086/118] =?UTF-8?q?Update=200450.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加代码高亮 --- problems/0450.删除二叉搜索树中的节点.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 8922a14e..60dae7b9 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -42,7 +42,7 @@ 代码如下: -``` +```cpp TreeNode* deleteNode(TreeNode* root, int key) ``` @@ -50,7 +50,7 @@ TreeNode* deleteNode(TreeNode* root, int key) 遇到空返回,其实这也说明没找到删除的节点,遍历到空节点直接返回了 -``` +```cpp if (root == nullptr) return root; ``` @@ -106,7 +106,7 @@ if (root->val == key) { 这里相当于把新的节点返回给上一层,上一层就要用 root->left 或者 root->right接住,代码如下: -``` +```cpp if (root->val > key) root->left = deleteNode(root->left, key); if (root->val < key) root->right = deleteNode(root->right, key); return root; From 6fdcc59aec48b8c3bb02dcc90b6709fd2ae566d2 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 20:26:57 +0800 Subject: [PATCH 087/118] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E6=93=8D=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加代码高亮 --- problems/0701.二叉搜索树中的插入操作.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 98e60d5f..5cb0de99 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -59,7 +59,7 @@ 代码如下: -``` +```cpp TreeNode* insertIntoBST(TreeNode* root, int val) ``` @@ -69,7 +69,7 @@ TreeNode* insertIntoBST(TreeNode* root, int val) 代码如下: -``` +```cpp if (root == NULL) { TreeNode* node = new TreeNode(val); return node; @@ -88,7 +88,7 @@ if (root == NULL) { 代码如下: -``` +```cpp if (root->val > val) root->left = insertIntoBST(root->left, val); if (root->val < val) root->right = insertIntoBST(root->right, val); return root; @@ -120,7 +120,7 @@ public: 那么递归函数定义如下: -``` +```cpp TreeNode* parent; // 记录遍历节点的父节点 void traversal(TreeNode* cur, int val) ``` From 2da3afe8a9c576fdb7f4d784b92e0fd7ce9b3074 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 21:28:45 +0800 Subject: [PATCH 088/118] Update gitserver.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正错别字和语病 --- problems/qita/gitserver.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/qita/gitserver.md b/problems/qita/gitserver.md index 9ee06ae4..f4108988 100644 --- a/problems/qita/gitserver.md +++ b/problems/qita/gitserver.md @@ -138,7 +138,7 @@ passwd gitpassword 创建`.ssh` 目录,如果`.ssh` 已经存在了,可以忽略这一项 -为啥用配置ssh公钥呢,同学们记不记得我急使用github上传上传代码的时候也要把自己的公钥配置上github上 +为啥用配置ssh公钥呢,同学们记不记得我使用github上传代码的时候也要把自己的公钥配置上github上 这也是方面每次操作git仓库的时候不用再去输入密码 @@ -186,7 +186,7 @@ cd /home/git/.ssh/ cat id_rsa.pub >> authorized_keys ``` -如何看我们配置的密钥是否成功呢, 在客户点直接登录git服务器,看看是否是免密登陆 +如何看我们配置的密钥是否成功呢, 在客户端直接登录git服务器,看看是否是免密登陆 ``` ssh git@git服务器ip ``` From e361eddeddf3c86ed53b360861fb90703d7e95ce Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 21:58:01 +0800 Subject: [PATCH 089/118] =?UTF-8?q?Update=20=E5=9B=BE=E8=AE=BA=E5=B9=B6?= =?UTF-8?q?=E6=9F=A5=E9=9B=86=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正语病 --- problems/图论并查集理论基础.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/图论并查集理论基础.md b/problems/图论并查集理论基础.md index a65d4807..6a1456e9 100644 --- a/problems/图论并查集理论基础.md +++ b/problems/图论并查集理论基础.md @@ -396,7 +396,7 @@ void join(int u, int v) { if (rank[u] <= rank[v]) father[u] = v; // rank小的树合入到rank大的树 else father[v] = u; - if (rank[u] == rank[v] && u != v) rank[v]++; // 如果两棵树高度相同,则v的高度+1因为,上面 if (rank[u] <= rank[v]) father[u] = v; 注意是 <= + if (rank[u] == rank[v] && u != v) rank[v]++; // 如果两棵树高度相同,则v的高度+1,因为上面 if (rank[u] <= rank[v]) father[u] = v; 注意是 <= } ``` From bf256aad79dcb8efcab4adfa60cc05d3a9c03f1f Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 21:59:12 +0800 Subject: [PATCH 090/118] Update gitserver.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正语病 --- problems/qita/gitserver.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/qita/gitserver.md b/problems/qita/gitserver.md index f4108988..caf93ec6 100644 --- a/problems/qita/gitserver.md +++ b/problems/qita/gitserver.md @@ -138,7 +138,7 @@ passwd gitpassword 创建`.ssh` 目录,如果`.ssh` 已经存在了,可以忽略这一项 -为啥用配置ssh公钥呢,同学们记不记得我使用github上传代码的时候也要把自己的公钥配置上github上 +为啥用配置ssh公钥呢,同学们记不记得我使用github上传代码的时候也要把自己的公钥配置上传到github上 这也是方面每次操作git仓库的时候不用再去输入密码 From af5741fbaad53da909a759f3f16765aa0049278c Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 22:43:48 +0800 Subject: [PATCH 091/118] =?UTF-8?q?Update=20On=E7=9A=84=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E5=B1=85=E7=84=B6=E8=B6=85=E6=97=B6=E4=BA=86=EF=BC=8C=E6=AD=A4?= =?UTF-8?q?=E6=97=B6=E7=9A=84n=E7=A9=B6=E7=AB=9F=E6=98=AF=E5=A4=9A?= =?UTF-8?q?=E5=A4=A7=EF=BC=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正错别字 --- problems/前序/On的算法居然超时了,此时的n究竟是多大?.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md index 8b0934c5..df488323 100644 --- a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md @@ -29,7 +29,7 @@ 所以 1GHz = 10亿Hz,表示CPU可以一秒脉冲10亿次(有10亿个时钟周期),这里不要简单理解一个时钟周期就是一次CPU运算。 -例如1 + 2 = 3,cpu要执行四次才能完整这个操作,步骤一:把1放入寄存机,步骤二:把2放入寄存器,步骤三:做加法,步骤四:保存3。 +例如1 + 2 = 3,cpu要执行四次才能完整这个操作,步骤一:把1放入寄存器,步骤二:把2放入寄存器,步骤三:做加法,步骤四:保存3。 而且计算机的cpu也不会只运行我们自己写的程序上,同时cpu也要执行计算机的各种进程任务等等,我们的程序仅仅是其中的一个进程而已。 From 7ac6785eb3f7450ffda868ea3149bb7bdfa6b965 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 27 Feb 2024 22:49:34 +0800 Subject: [PATCH 092/118] =?UTF-8?q?Update=20On=E7=9A=84=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E5=B1=85=E7=84=B6=E8=B6=85=E6=97=B6=E4=BA=86=EF=BC=8C=E6=AD=A4?= =?UTF-8?q?=E6=97=B6=E7=9A=84n=E7=A9=B6=E7=AB=9F=E6=98=AF=E5=A4=9A?= =?UTF-8?q?=E5=A4=A7=EF=BC=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正语病 --- problems/前序/On的算法居然超时了,此时的n究竟是多大?.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md index df488323..d5710d5a 100644 --- a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md @@ -52,7 +52,7 @@ * 火箭科学家需要大致知道一枚试射火箭的着陆点是在大海里还是在城市中; * 医学研究者需要知道一次药物测试是会杀死还是会治愈实验对象; -所以**任何开发计算机程序员的软件工程师都应该能够估计这个程序的运行时间是一秒钟还是一年**。 +所以**任何开发计算机程序的软件工程师都应该能够估计这个程序的运行时间是一秒钟还是一年**。 这个是最基本的,所以以上误差就不算事了。 From dd242cfbb5339ef8d03b0911da3b57d9b2da9bed Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 29 Feb 2024 19:52:04 +0800 Subject: [PATCH 093/118] =?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 0435.无重叠区间C语言实现 --- problems/0435.无重叠区间.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index cf9996dd..b668e860 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -441,7 +441,37 @@ impl Solution { } } ``` +### C + +```c +// 按照区间右边界排序 +int cmp(const void * var1, const void * var2){ + return (*(int **) var1)[1] - (*(int **) var2)[1]; +} + +int eraseOverlapIntervals(int** intervals, int intervalsSize, int* intervalsColSize) { + if(intervalsSize == 0){ + return 0; + } + qsort(intervals, intervalsSize, sizeof (int *), cmp); + // 记录非重叠的区间数量 + int count = 1; + // 记录区间分割点 + int end = intervals[0][1]; + for(int i = 1; i < intervalsSize; i++){ + if(end <= intervals[i][0]){ + end = intervals[i][1]; + count++; + } + } + return intervalsSize - count; +} +``` + + + ### C# + ```csharp public class Solution { @@ -468,3 +498,4 @@ public class Solution + From 3c4632315c64a4ed47857dd66a8e86bba77e19cd Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 29 Feb 2024 20:14:04 +0800 Subject: [PATCH 094/118] =?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 0763.划分字母区间增加C语言实现 --- problems/0763.划分字母区间.md | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md index 4e9ec578..8b0ca7b8 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -404,7 +404,38 @@ impl Solution { } } ``` +### C + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int* partitionLabels(char* s, int* returnSize) { + // 记录每个字符最远出现的位置 + int last[26] = {0}; + int len = strlen(s); + for (int i = 0; i < len; ++i) { + last[s[i] - 'a'] = i; + } + int left = 0, right = 0; + int * partition = malloc(sizeof (int ) * len); + // 初始化值 + *returnSize = 0; + for(int i = 0; i < len; i++){ + right = max(right, last[s[i] - 'a']); + // 到达最远位置,加入答案,并且更新左边下标 + if(i == right){ + partition[(*returnSize)++] = right - left + 1; + left = i + 1; + } + } + return partition; +} +``` + + + ### C# + ```csharp public class Solution { @@ -435,4 +466,3 @@ public class Solution - From 48e65c1de98e473f9a3e93161f0f484c5b13ed1e Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 29 Feb 2024 20:44:07 +0800 Subject: [PATCH 095/118] =?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 0056.合并区间新增C语言实现 --- problems/0056.合并区间.md | 43 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index 122e783a..f9d6f654 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -336,7 +336,49 @@ impl Solution { } } ``` +### C + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +// 根据左边界进行排序 +int cmp(const void * var1, const void * var2){ + int *v1 = *(int **) var1; + int *v2 = *(int **) var2; + return v1[0] - v2[0]; +} + +int** merge(int** intervals, int intervalsSize, int* intervalsColSize, int* returnSize, int** returnColumnSizes) { + int ** result = malloc(sizeof (int *) * intervalsSize); + * returnColumnSizes = malloc(sizeof (int ) * intervalsSize); + for(int i = 0; i < intervalsSize; i++){ + result[i] = malloc(sizeof (int ) * 2); + } + qsort(intervals, intervalsSize, sizeof (int *), cmp); + int count = 0; + for(int i = 0; i < intervalsSize; i++){ + // 记录区间的左右边界 + int L = intervals[i][0], R = intervals[i][1]; + // 如果count为0或者前一区间的右区间小于此时的左边,加入结果中 + if (count == 0 || result[count - 1][1] < L) { + returnColumnSizes[0][count] = 2; + result[count][0] = L; + result[count][1] = R; + count++; + } + else{ // 更新右边界的值 + result[count - 1][1] = max(R, result[count - 1][1]); + } + } + *returnSize = count; + return result; +} +``` + + + ### C# + ```csharp public class Solution { @@ -367,4 +409,3 @@ public class Solution - From 64399ddf6f997b627615a82e791ff50bcf3c2811 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 29 Feb 2024 20:55:06 +0800 Subject: [PATCH 096/118] =?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 0738.单调递增的数字增加C语言实现 --- problems/0738.单调递增的数字.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index 400dc90d..4a8a6e08 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -392,7 +392,33 @@ impl Solution { } } ``` +### C + +```c +int monotoneIncreasingDigits(int n) { + char str[11]; + // 将数字转换为字符串 + sprintf(str, "%d", n); + int len = strlen(str); + int flag = strlen(str); + for(int i = len - 1; i > 0; i--){ + if(str[i] < str[i - 1]){ + str[i - 1]--; + flag = i; + } + } + for(int i = flag; i < len; i++){ + str[i] = '9'; + } + // 字符串转数字 + return atoi(str); +} +``` + + + ### C# + ```csharp public class Solution { @@ -421,4 +447,3 @@ public class Solution - From d6a37be6f21083a1e4bcae7fe167c1bca583fee4 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 7 Mar 2024 20:03:10 +0800 Subject: [PATCH 097/118] =?UTF-8?q?Update=200494.=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0494.目标和新增C语言实现 --- problems/0494.目标和.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index e7a05d45..8d1a34e5 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -585,7 +585,42 @@ impl Solution { } } ``` +```c +int getSum(int * nums, int numsSize){ + int sum = 0; + for(int i = 0; i < numsSize; i++){ + sum += nums[i]; + } + return sum; +} + +int findTargetSumWays(int* nums, int numsSize, int target) { + int sum = getSum(nums, numsSize); + int diff = sum - target; + // 两种情况不满足 + if(diff < 0 || diff % 2 != 0){ + return 0; + } + int bagSize = diff / 2; + int dp[numsSize + 1][bagSize + 1]; + dp[0][0] = 1; + for(int i = 1; i <= numsSize; i++){ + int num = nums[i - 1]; + for(int j = 0; j <= bagSize; j++){ + dp[i][j] = dp[i - 1][j]; + if(j >= num){ + dp[i][j] += dp[i - 1][j - num]; + } + } + } + return dp[numsSize][bagSize]; +} +``` + + + ### C# + ```csharp public class Solution { @@ -617,4 +652,3 @@ public class Solution - From 0a30cd7a2664cc8198635bf0c69447abe3c57fa4 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 7 Mar 2024 20:04:45 +0800 Subject: [PATCH 098/118] =?UTF-8?q?Update=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0474.一和零新增C语言实现 --- problems/0474.一和零.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 904d941e..7e04ae1e 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -533,7 +533,39 @@ impl Solution { } } ``` +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int findMaxForm(char** strs, int strsSize, int m, int n) { + int dp[m + 1][n + 1]; + memset(dp, 0, sizeof (int ) * (m + 1) * (n + 1)); + for(int i = 0; i < strsSize; i++){ + // 统计0和1的数量 + int count0 = 0; + int count1 = 0; + char *str = strs[i]; + while (*str != '\0'){ + if(*str == '0'){ + count0++; + } else{ + count1++; + } + str++; + } + for(int j = m; j >= count0; j--){ + for(int k = n; k >= count1; k--){ + dp[j][k] = max(dp[j][k], dp[j - count0][k - count1] + 1); + } + } + } + return dp[m][n]; +} +``` + + + ### C# + ```csharp public class Solution { @@ -565,4 +597,3 @@ public class Solution - From 4e7637556b14e6600a73928269d324bc227e08ab Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 7 Mar 2024 20:13:39 +0800 Subject: [PATCH 099/118] =?UTF-8?q?Update=200518.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0518.零钱兑换II新增C语言实现 --- problems/0518.零钱兑换II.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index da1c4755..59fdf6cd 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -353,7 +353,28 @@ object Solution { } } ``` +## C + +```c +int change(int amount, int* coins, int coinsSize) { + int dp[amount + 1]; + memset(dp, 0, sizeof (dp)); + dp[0] = 1; + // 遍历物品 + for(int i = 0; i < coinsSize; i++){ + // 遍历背包 + for(int j = coins[i]; j <= amount; j++){ + dp[j] += dp[j - coins[i]]; + } + } + return dp[amount]; +} +``` + + + ### C# + ```csharp public class Solution { @@ -378,3 +399,4 @@ public class Solution + From 12365a3a4fcd4a38633921df6c942c8a7c7536f9 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 7 Mar 2024 20:15:51 +0800 Subject: [PATCH 100/118] =?UTF-8?q?Update=200474.=E4=B8=80=E5=92=8C?= =?UTF-8?q?=E9=9B=B6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0474.一和零.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 7e04ae1e..af50fa5c 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -533,6 +533,8 @@ impl Solution { } } ``` +## C + ```c #define max(a, b) ((a) > (b) ? (a) : (b)) @@ -597,3 +599,4 @@ public class Solution + From 702916f35626f98841b0700b8bce8688e8fc7c7a Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Thu, 7 Mar 2024 20:16:56 +0800 Subject: [PATCH 101/118] =?UTF-8?q?Update=200494.=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0494.目标和.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 8d1a34e5..02edad4d 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -585,6 +585,8 @@ impl Solution { } } ``` +## C + ```c int getSum(int * nums, int numsSize){ int sum = 0; @@ -652,3 +654,4 @@ public class Solution + From a55dca64eda06deac1fac7e291df3a2694006cce Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Fri, 8 Mar 2024 22:40:51 +0800 Subject: [PATCH 102/118] =?UTF-8?q?=E6=96=B0=E5=A2=9EC=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0279.完全平方数.md | 25 ++++++++++++++++++++++++- problems/0322.零钱兑换.md | 30 +++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index a0e62d48..f7c06dbd 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -389,6 +389,30 @@ function numSquares(n: number): number { }; ``` +## C + +```c +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int numSquares(int n) { + int* dp = (int*)malloc(sizeof(int) * (n + 1)); + for (int j = 0; j < n + 1; j++) { + dp[j] = INT_MAX; + } + dp[0] = 0; + // 遍历背包 + for (int i = 0; i <= n; ++i) { + // 遍历物品 + for (int j = 1; j * j <= i; ++j) { + dp[i] = min(dp[i - j * j] + 1, dp[i]); + } + } + return dp[n]; +} +``` + + + ### Rust: ```rust @@ -439,4 +463,3 @@ impl Solution { - diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index eae4ab3a..156b5ff3 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -352,6 +352,35 @@ func min(a, b int) int { ``` +## C + +```c +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int coinChange(int* coins, int coinsSize, int amount) { + int* dp = (int*)malloc(sizeof(int) * (amount + 1)); + for (int j = 0; j < amount + 1; j++) { + dp[j] = INT_MAX; + } + dp[0] = 0; + // 遍历背包 + for(int i = 0; i <= amount; i++){ + // 遍历物品 + for(int j = 0; j < coinsSize; j++){ + if(i - coins[j] >= 0 && dp[i - coins[j]] != INT_MAX){ + dp[i] = min(dp[i], dp[i - coins[j]] + 1); + } + } + } + if(dp[amount] == INT_MAX){ + return -1; + } + return dp[amount]; +} +``` + + + ### Rust: ```rust @@ -474,4 +503,3 @@ function coinChange(coins: number[], amount: number): number { - From 6bae30472cf1e0380c3a6652b877ff7777d3f993 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Fri, 8 Mar 2024 22:42:26 +0800 Subject: [PATCH 103/118] =?UTF-8?q?Update=200377.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8C=E2=85=A3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增C语言实现 --- problems/0377.组合总和Ⅳ.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index a840ec9b..6f81bffe 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -312,7 +312,28 @@ impl Solution { } } ``` +### C + +```c +int combinationSum4(int* nums, int numsSize, int target) { + int dp[target + 1]; + memset(dp, 0, sizeof (dp )); + dp[0] = 1; + for(int i = 0; i <= target; i++){ + for(int j = 0; j < numsSize; j++){ + if(i - nums[j] >= 0 && dp[i] < INT_MAX - dp[i - nums[j]]){ + dp[i] += dp[i - nums[j]]; + } + } + } + return dp[target]; +} +``` + + + ### C# + ```csharp public class Solution { @@ -340,4 +361,3 @@ public class Solution - From 216f9db871f5c08a8b44573c678eab3915aa9f49 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sat, 9 Mar 2024 17:15:37 +0800 Subject: [PATCH 104/118] =?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 0139.单词拆分新增C语言实现 --- problems/0139.单词拆分.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index d93288ae..a3d59ec7 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -498,6 +498,33 @@ function wordBreak(s: string, wordDict: string[]): boolean { }; ``` +### C + +```c +bool wordBreak(char* s, char** wordDict, int wordDictSize) { + int len = strlen(s); + // 初始化 + bool dp[len + 1]; + memset(dp, false, sizeof (dp)); + dp[0] = true; + for (int i = 1; i < len + 1; ++i) { + for(int j = 0; j < wordDictSize; j++){ + int wordLen = strlen(wordDict[j]); + // 分割点是由i和字典单词长度决定 + int k = i - wordLen; + if(k < 0){ + continue; + } + // 这里注意要限制长度,故用strncmp + dp[i] = (dp[k] && !strncmp(s + k, wordDict[j], wordLen)) || dp[i]; + } + } + return dp[len]; +} +``` + + + ### Rust: ```rust @@ -521,4 +548,3 @@ impl Solution { - From bc6189e9e9898c72180f1787f7614e0c95d0181f Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sun, 10 Mar 2024 17:50:38 +0800 Subject: [PATCH 105/118] =?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 0198.打家劫舍新增C语言实现 --- problems/0198.打家劫舍.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index a7bc4c99..480222ef 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -315,6 +315,31 @@ function rob(nums: number[]): number { }; ``` +### C + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int rob(int* nums, int numsSize) { + if(numsSize == 0){ + return 0; + } + if(numsSize == 1){ + return nums[0]; + } + // dp初始化 + int dp[numsSize]; + dp[0] = nums[0]; + dp[1] = max(nums[0], nums[1]); + for(int i = 2; i < numsSize; i++){ + dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); + } + return dp[numsSize - 1]; +} +``` + + + ### Rust: ```rust @@ -339,3 +364,4 @@ impl Solution { + From 2cee392d8e4ad3064a8d437017bb4e8895ad7477 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sun, 10 Mar 2024 17:56:42 +0800 Subject: [PATCH 106/118] =?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 0213.打家劫舍||新增C语言实现 --- problems/0213.打家劫舍II.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 385c5867..ba996f2b 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -308,6 +308,34 @@ function robRange(nums: number[], start: number, end: number): number { } ``` +### C + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +// 198.打家劫舍的逻辑 +int robRange(int* nums, int start, int end, int numsSize) { + if (end == start) return nums[start]; + int dp[numsSize]; + dp[start] = nums[start]; + dp[start + 1] = max(nums[start], nums[start + 1]); + for (int i = start + 2; i <= end; i++) { + dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]); + } + return dp[end]; +} + +int rob(int* nums, int numsSize) { + if (numsSize == 0) return 0; + if (numsSize == 1) return nums[0]; + int result1 = robRange(nums, 0, numsSize - 2, numsSize); // 情况二 + int result2 = robRange(nums, 1, numsSize - 1, numsSize); // 情况三 + return max(result1, result2); +} +``` + + + ### Rust: ```rust @@ -343,4 +371,3 @@ impl Solution { - From 0dc2180cee3c015a91ab0906858f544efadd7d24 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sun, 10 Mar 2024 21:44:04 +0800 Subject: [PATCH 107/118] =?UTF-8?q?Update=200337.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8DIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0337.打家劫舍|||新增C语言实现 --- problems/0337.打家劫舍III.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index f616ec74..61b9f99c 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -490,6 +490,33 @@ function robNode(node: TreeNode | null): MaxValueArr { } ``` +### C + +```c +int *robTree(struct TreeNode *node) { + int* amounts = (int*) malloc(sizeof(int) * 2); + memset(amounts, 0, sizeof(int) * 2); + if(node == NULL){ + return amounts; + } + int * left = robTree(node->left); + int * right = robTree(node->right); + // 偷当前节点 + amounts[1] = node->val + left[0] + right[0]; + // 不偷当前节点 + amounts[0] = max(left[0], left[1]) + max(right[0], right[1]); + return amounts; +} + +int rob(struct TreeNode* root) { + int * dp = robTree(root); + // 0代表不偷当前节点可以获得的最大值,1表示偷当前节点可以获取的最大值 + return max(dp[0], dp[1]); +} +``` + + + ### Rust 动态规划: @@ -523,4 +550,3 @@ impl Solution { - From b6e458bcfa3be2f8b7f282f5918f9bc26512e9fd Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Sun, 10 Mar 2024 21:47:48 +0800 Subject: [PATCH 108/118] =?UTF-8?q?Update=200121.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0121.买卖股票的最佳时机新增C语言实现 --- problems/0121.买卖股票的最佳时机.md | 47 ++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index cbdf40e8..fb548cbc 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -531,6 +531,52 @@ public class Solution } ``` +### C: + +> 贪心 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int maxProfit(int* prices, int pricesSize) { + int low = INT_MIN; + int result = 0; + for(int i = 0; i < pricesSize; i++){ + low = min(low, prices[i]); + result = max(result, prices[i] - low); + } + return result; +} +``` + +> 动态规划 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int* prices, int pricesSize){ + if(pricesSize == 0){ + return 0; + } + // dp初始化 + int ** dp = malloc(sizeof (int *) * pricesSize); + for(int i = 0; i < pricesSize; i++){ + dp[i] = malloc(sizeof (int ) * 2); + } + // 下标0表示持有股票的情况下的最大现金,下标1表示不持有股票的情况下获得的最大现金 + dp[0][0] = -prices[0]; + dp[0][1] = 0; + for(int i = 1; i < pricesSize; i++){ + dp[i][0] = max(dp[i - 1][0], - prices[i]); + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]); + } + return dp[pricesSize - 1][1]; +} +``` + + + ### Rust: > 贪心 @@ -568,4 +614,3 @@ impl Solution { - From cb58e8afa198a4b9abf57e0e3d76383d850b2d43 Mon Sep 17 00:00:00 2001 From: sss1h <49825610+sss1h@users.noreply.github.com> Date: Tue, 12 Mar 2024 20:20:00 +0800 Subject: [PATCH 109/118] =?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 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index f508b523..2fcfd283 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -82,7 +82,7 @@ public: // ListNode *tmp = slow->next; C++释放内存的逻辑 // slow->next = tmp->next; - // delete nth; + // delete tmp; return dummyHead->next; } From 57e56c508b567c453945b3398dc84c83002d6ec0 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:39:58 +0800 Subject: [PATCH 110/118] =?UTF-8?q?Update=200714.=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?=E5=90=AB=E6=89=8B=E7=BB=AD=E8=B4=B9=EF=BC=88=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=EF=BC=89.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0714.买卖股票的最佳时机含手续费新增C语言实现 --- ....买卖股票的最佳时机含手续费(动态规划).md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 7e8e3d7c..88ba9271 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -247,7 +247,29 @@ function maxProfit(prices: number[], fee: number): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +// dp[i][0] 表示第i天持有股票所省最多现金。 +// dp[i][1] 表示第i天不持有股票所得最多现金 +int maxProfit(int* prices, int pricesSize, int fee) { + int dp[pricesSize][2]; + dp[0][0] = -prices[0]; + dp[0][1] = 0; + for (int i = 1; i < pricesSize; ++i) { + dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]); + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee); + } + return dp[pricesSize - 1][1]; +} +``` + + + ### Rust: + **贪心** ```Rust @@ -304,3 +326,4 @@ impl Solution { + From 1b9ae455df706c170e6af3c73543a15f8fdbef79 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:43:13 +0800 Subject: [PATCH 111/118] =?UTF-8?q?Update=200122.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?II=EF=BC=88=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=EF=BC=89.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0122.买卖股票的最佳时机II新增C语言实现 --- .../0122.买卖股票的最佳时机II(动态规划).md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 6e08b57c..24c7f168 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -365,6 +365,49 @@ public class Solution } ``` +### C: + +> 动态规划 + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int* prices, int pricesSize){ + int **dp = malloc(sizeof (int *) * pricesSize); + for (int i = 0; i < pricesSize; ++i) { + dp[i] = malloc(sizeof (int ) * 2); + } + // 0表示持有该股票所得最大,1表示不持有所得最大 + dp[0][0] = -prices[0]; + dp[0][1] = 0; + for (int i = 1; i < pricesSize; ++i) { + dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]); + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]); + } + return dp[pricesSize - 1][1]; +} +``` + +> 贪心 + +```c +int maxProfit(int* prices, int pricesSize) { + if(pricesSize == 0){ + return 0; + } + int result = 0; + for(int i = 1; i < pricesSize; i++){ + // 如果今天股票价格大于昨天,代表有利润 + if(prices[i] > prices[i - 1]){ + result += prices[i] - prices[i - 1]; + } + } + return result; +} +``` + + + ### Rust: > 贪心 @@ -416,3 +459,4 @@ impl Solution { + From d40d61e265e33deddc2d84daacd52eb85afb5496 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:44:50 +0800 Subject: [PATCH 112/118] =?UTF-8?q?Update=200123.=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?III.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0123.买卖股票的最佳时机III新增C语言实现 --- problems/0123.买卖股票的最佳时机III.md | 29 +++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 72dd9042..18f19c51 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -413,6 +413,34 @@ function maxProfit(prices: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int maxProfit(int* prices, int pricesSize) { + int buy1 = prices[0], buy2 = prices[0]; + int profit1 = 0, profit2 = 0; + for (int i = 0; i < pricesSize; ++i) { + // 寻找最低点买入 + buy1 = min(buy1, prices[i]); + // 找到第一次交易的最大盈利,并不断维护这一最大值 + profit1 = max(profit1, prices[i] - buy1); + + // 寻找第二次交易的最低投资点,并且考虑前一次交易的成本 + // 当前价格 - 第一次操作的盈利=新的投入成本( + // 为了让盈利最大,要寻找最小的成本) + buy2 = min(buy2, prices[i] - profit1); + // 第二次卖出后的盈利:当前价格减去成本,不断维护这一最大的总利润 + profit2 = max(profit2, prices[i] - buy2); + } + return profit2; +} +``` + + + ### Rust: > 版本一 @@ -465,4 +493,3 @@ impl Solution { - From d91656d036e536637138ebe7c51c8a37eda01bc2 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:46:06 +0800 Subject: [PATCH 113/118] =?UTF-8?q?Update=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0188.买卖股票的最佳时机IV新增C语言实现 --- problems/0188.买卖股票的最佳时机IV.md | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index e4c5c484..2521749f 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -474,6 +474,34 @@ function maxProfit(k: number, prices: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int k, int* prices, int pricesSize) { + if(pricesSize == 0){ + return 0; + } + + int dp[pricesSize][2 * k + 1]; + memset(dp, 0, sizeof(int) * pricesSize * (2 * k + 1)); + for (int j = 1; j < 2 * k; j += 2) { + dp[0][j] = -prices[0]; + } + + for (int i = 1;i < pricesSize; i++) {//枚举股票 + for (int j = 0; j < 2 * k - 1; j += 2) { //更新每一次买入卖出 + dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]); + dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]); + } + } + return dp[pricesSize - 1][2 * k]; +} +``` + + + ### Rust: ```rust @@ -529,3 +557,4 @@ impl Solution { + From ec899d684b31e7fee9ba80836ec9683084d5dacb Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:47:38 +0800 Subject: [PATCH 114/118] =?UTF-8?q?Update=200309.=E6=9C=80=E4=BD=B3?= =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E6=97=B6=E6=9C=BA=E5=90=AB?= =?UTF-8?q?=E5=86=B7=E5=86=BB=E6=9C=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0309.最佳买卖股票时机含冷冻期新增C语言实现 --- problems/0309.最佳买卖股票时机含冷冻期.md | 35 ++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 0eb66fb5..9dc35bdf 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -457,6 +457,40 @@ function maxProfit(prices: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +/** + * 状态一:持有股票状态(今天买入股票, + * 或者是之前就买入了股票然后没有操作,一直持有) + * 不持有股票状态,这里就有两种卖出股票状态 + * 状态二:保持卖出股票的状态(两天前就卖出了股票,度过一天冷冻期。 + * 或者是前一天就是卖出股票状态,一直没操作) + * 状态三:今天卖出股票 + * 状态四:今天为冷冻期状态,但冷冻期状态不可持续,只有一天! + + */ +int maxProfit(int* prices, int pricesSize) { + if(pricesSize == 0){ + return 0; + } + int dp[pricesSize][4]; + memset(dp, 0, sizeof (int ) * pricesSize * 4); + dp[0][0] = -prices[0]; + for (int i = 1; i < pricesSize; ++i) { + dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][1] - prices[i], dp[i - 1][3] - prices[i])); + dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]); + dp[i][2] = dp[i - 1][0] + prices[i]; + dp[i][3] = dp[i - 1][2]; + } + return max(dp[pricesSize - 1][1], max(dp[pricesSize - 1][2], dp[pricesSize - 1][3])); +} +``` + + + ### Rust: ```rust @@ -486,4 +520,3 @@ impl Solution { - From 5f07ae3b033644dc6cbcf96c23eeef136ed4a5b0 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Wed, 13 Mar 2024 22:00:54 +0800 Subject: [PATCH 115/118] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0300.最长上升子序列的新增C语言实现 --- problems/0300.最长上升子序列.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index 64f75291..6d82eae1 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -288,6 +288,36 @@ function lengthOfLIS(nums: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int lengthOfLIS(int* nums, int numsSize) { + if(numsSize <= 1){ + return numsSize; + } + int dp[numsSize]; + for(int i = 0; i < numsSize; i++){ + dp[i]=1; + } + int result = 1; + for (int i = 1; i < numsSize; ++i) { + for (int j = 0; j < i; ++j) { + if(nums[i] > nums[j]){ + dp[i] = max(dp[i], dp[j] + 1); + } + if(dp[i] > result){ + result = dp[i]; + } + } + } + return result; +} +``` + + + ### Rust: ```rust @@ -311,4 +341,3 @@ pub fn length_of_lis(nums: Vec) -> i32 { - From bf457f49bb1961bc0013283b8b9678363a9a7207 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Wed, 13 Mar 2024 22:04:23 +0800 Subject: [PATCH 116/118] =?UTF-8?q?Update=200674.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E8=BF=9E=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0674.最长连续递增序列新增C语言实现 --- problems/0674.最长连续递增序列.md | 52 ++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 485e321c..ece62944 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -425,6 +425,57 @@ function findLengthOfLCIS(nums: number[]): number { }; ``` +### C: + +> 动态规划: + +```c +int findLengthOfLCIS(int* nums, int numsSize) { + if(numsSize == 0){ + return 0; + } + int dp[numsSize]; + for(int i = 0; i < numsSize; i++){ + dp[i] = 1; + } + int result = 1; + for (int i = 1; i < numsSize; ++i) { + if(nums[i] > nums[i - 1]){ + dp[i] = dp[i - 1] + 1; + } + if(dp[i] > result){ + result = dp[i]; + } + } + return result; +} +``` + + + +> 贪心: + +```c +int findLengthOfLCIS(int* nums, int numsSize) { + int result = 1; + int count = 1; + if(numsSize == 0){ + return result; + } + for (int i = 1; i < numsSize; ++i) { + if(nums[i] > nums[i - 1]){ + count++; + } else{ + count = 1; + } + if(count > result){ + result = count; + } + } + return result; +} +``` + @@ -432,4 +483,3 @@ function findLengthOfLCIS(nums: number[]): number { - From 00a5515bad938f6c3ff32e3f88c5639346c0f947 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Wed, 13 Mar 2024 22:05:38 +0800 Subject: [PATCH 117/118] =?UTF-8?q?Update=200718.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=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 0178.最长重复子数组新增C语言实现 --- problems/0718.最长重复子数组.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 272cf2b2..e00b3ded 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -560,10 +560,30 @@ impl Solution { } ``` +### C: + +```c +int findLength(int* nums1, int nums1Size, int* nums2, int nums2Size) { + int dp[nums1Size + 1][nums2Size + 1]; + memset(dp, 0, sizeof(dp)); + int result = 0; + for (int i = 1; i <= nums1Size; ++i) { + for (int j = 1; j <= nums2Size; ++j) { + if(nums1[i - 1] == nums2[j - 1]){ + dp[i][j] = dp[i - 1][j - 1] + 1; + } + if(dp[i][j] > result){ + result = dp[i][j]; + } + } + } + return result; +} +``` +

- From fac689939f7c6a31f11198a4ecccfa3d0f2bee6a Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Wed, 13 Mar 2024 22:08:15 +0800 Subject: [PATCH 118/118] =?UTF-8?q?Update=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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1143.最长公共子序列新增C语言实现 --- problems/1143.最长公共子序列.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index f33391c3..12bd90f8 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -376,10 +376,32 @@ impl Solution { } ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int longestCommonSubsequence(char* text1, char* text2) { + int text1Len = strlen(text1); + int text2Len = strlen(text2); + int dp[text1Len + 1][text2Len + 1]; + memset(dp, 0, sizeof (dp)); + for (int i = 1; i <= text1Len; ++i) { + for (int j = 1; j <= text2Len; ++j) { + if(text1[i - 1] == text2[j - 1]){ + dp[i][j] = dp[i - 1][j - 1] + 1; + } else{ + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[text1Len][text2Len]; +} +``` +

-