From fe1eaeff4e10f6533a41539bf0e99f32021f1cc3 Mon Sep 17 00:00:00 2001 From: freshield Date: Tue, 11 Oct 2022 19:56:58 +0800 Subject: [PATCH 01/33] =?UTF-8?q?=E6=9B=B4=E6=96=B0python3=E7=9A=84?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=EF=BC=8C=E6=9B=BF=E6=8D=A2list=E4=B8=BAdeque?= =?UTF-8?q?=EF=BC=8C=E5=A6=82=E6=9E=9C=E7=94=A8list=E4=BC=9A=E8=B6=85?= =?UTF-8?q?=E6=97=B6=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 3f402f12..b86fdd15 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -296,16 +296,19 @@ class Solution { ``` Python: -```python +```python3 +from collections import deque + + class MyQueue: #单调队列(从大到小 def __init__(self): - self.queue = [] #使用list来实现单调队列 + self.queue = deque() #这里需要使用deque实现单调队列,直接使用list会超时 #每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。 #同时pop之前判断队列当前是否为空。 def pop(self, value): if self.queue and value == self.queue[0]: - self.queue.pop(0)#list.pop()时间复杂度为O(n),这里可以使用collections.deque() + self.queue.popleft()#list.pop()时间复杂度为O(n),这里需要使用collections.deque() #如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。 #这样就保持了队列里的数值是单调从大到小的了。 From b17f747202cffed777cafb9c31db771e8142dd93 Mon Sep 17 00:00:00 2001 From: baozi Date: Tue, 11 Oct 2022 22:20:09 +0800 Subject: [PATCH 02/33] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97=20=E6=94=B6=E7=9B=8A--=E5=8F=97=E7=9B=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3dbf2c0d..fb3d625c 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ 我在题目讲解中统一使用C++,但你会发现下面几乎每篇题解都配有其他语言版本,Java、Python、Go、JavaScript等等,正是这些[热心小伙们](https://github.com/youngyangyang04/leetcode-master/graphs/contributors)的贡献的代码,当然我也会严格把控代码质量。 -**所以也欢迎大家参与进来,完善题解的各个语言版本,拥抱开源,让更多小伙伴们收益**。 +**所以也欢迎大家参与进来,完善题解的各个语言版本,拥抱开源,让更多小伙伴们受益**。 准备好了么,刷题攻略开始咯,go go go! From 12eb9158c3b1e7148add297d289176d4543cfb15 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 10:19:54 -0600 Subject: [PATCH 03/33] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D?= =?UTF-8?q?=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0701.二叉搜索树中的插入操作.md python3 迭代法优化 --- problems/0701.二叉搜索树中的插入操作.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 06e1c88f..599dd073 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -337,16 +337,15 @@ class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val) - parent = None + parent = None # 此步可以省略 cur = root # 用while循环不断地找新节点的parent while cur: + parent = cur # 首先保存当前非空节点作为下一次迭代的父节点 if cur.val < val: - parent = cur cur = cur.right elif cur.val > val: - parent = cur cur = cur.left # 运行到这意味着已经跳出上面的while循环, From 4671287dd3494c3b2d7592450e1c7c92f13d0504 Mon Sep 17 00:00:00 2001 From: jinzhongjia Date: Thu, 13 Oct 2022 00:34:44 +0800 Subject: [PATCH 04/33] =?UTF-8?q?Update=200084.=E6=9F=B1=E7=8A=B6=E5=9B=BE?= =?UTF-8?q?=E4=B8=AD=E6=9C=80=E5=A4=A7=E7=9A=84=E7=9F=A9=E5=BD=A2.md?= =?UTF-8?q?=EF=BC=8C=E5=A2=9E=E5=8A=A0goland=E7=9A=84=E5=8D=95=E8=B0=83?= =?UTF-8?q?=E6=A0=88=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0084.柱状图中最大的矩形.md | 39 +++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index e085e455..144b4027 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -409,7 +409,44 @@ class Solution: ``` -***** + +Go: + +> 单调栈 + +```go +func largestRectangleArea(heights []int) int { + // 声明max并初始化为0 + max := 0 + // 使用切片实现栈 + stack := make([]int, 0) + // 数组头部加入0 + heights = append([]int{0}, heights...) + // 数组尾部加入0 + heights = append(heights, 0) + // 初始化栈,序号从0开始 + stack = append(stack, 0) + for i := 1; i < len(heights); i++ { + // 结束循环条件为:当即将入栈元素>top元素,也就是形成非单调递增的趋势 + for heights[stack[len(stack)-1]] > heights[i] { + // mid 是top + mid := stack[len(stack)-1] + // 出栈 + stack = stack[0 : len(stack)-1] + // left是top的下一位元素,i是将要入栈的元素 + left := stack[len(stack)-1] + // 高度x宽度 + tmp := heights[mid] * (i - left - 1) + if tmp > max { + max = tmp + } + } + stack = append(stack, i) + } + return max +} + +``` JavaScript: ```javascript From f6db9d06e23986ea946d5108e2a921d261f1ef91 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 10:34:56 -0600 Subject: [PATCH 05/33] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D?= =?UTF-8?q?=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0701.二叉搜索树中的插入操作.md Python3 **递归法** - 无返回值 有注释 不用Helper function --- .../0701.二叉搜索树中的插入操作.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 599dd073..6a78b2b4 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -330,6 +330,27 @@ class Solution: return root ``` +**递归法** - 无返回值 有注释 不用Helper function +``` +class Solution: + last = None + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: # for root==None + return TreeNode(val) + if root.valval: + if root.left==None: # found the parent + root.left = TreeNode(val) + else: # not found, keep searching + self.insertIntoBST(root.left, val) + # return the final tree + return root +``` + **迭代法** 与无返回值的递归函数的思路大体一致 ```python From abb348dbc4dc6f0081ae313c23c1e3a408dfd818 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 10:38:50 -0600 Subject: [PATCH 06/33] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D?= =?UTF-8?q?=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0701.二叉搜索树中的插入操作.md Python3 **递归法** - 无返回值 有注释 不用Helper function - 删掉无用变量 增加python标志 --- problems/0701.二叉搜索树中的插入操作.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 6a78b2b4..a6f932b0 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -331,9 +331,8 @@ class Solution: ``` **递归法** - 无返回值 有注释 不用Helper function -``` +```python class Solution: - last = None def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: # for root==None return TreeNode(val) From bd77b3bb63445b8ab09d47a95ab7e4e07433b307 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 14:07:50 -0600 Subject: [PATCH 07/33] =?UTF-8?q?Update=200450.=E5=88=A0=E9=99=A4=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0450.删除二叉搜索树中的节点.md 添加python3迭代法 --- .../0450.删除二叉搜索树中的节点.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 2d6d4ef2..541c8be4 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -344,6 +344,48 @@ class Solution: return root ``` +**迭代法** +```python +class Solution: + def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: + # 找到节点后分两步,1. 把节点的左子树和右子树连起来,2. 把右子树跟父节点连起来 + # root is None + if not root: return root + p = root + last = None + while p: + if p.val==key: + # 1. connect left to right + # right is not None -> left is None | left is not None + if p.right: + if p.left: + node = p.right + while node.left: + node = node.left + node.left = p.left + right = p.right + else: + # right is None -> right=left + right = p.left + # 2. connect right to last + if last==None: + root = right + elif last.val>key: + last.left = right + else: + last.right = right + # 3. return + break + else: + # Update last and continue + last = p + if p.val>key: + p = p.left + else: + p = p.right + return root +``` + ## Go ```Go // 递归版本 From 3947eeaab9d868fbe4665629a1792c1c9cd3a593 Mon Sep 17 00:00:00 2001 From: L1Y1 <108316255+L1Y1@users.noreply.github.com> Date: Thu, 13 Oct 2022 17:00:01 +0800 Subject: [PATCH 08/33] =?UTF-8?q?Update=200235.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=A5=96=E5=85=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可以写的更通俗易懂一些 --- problems/0235.二叉搜索树的最近公共祖先.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 07e55ba5..a8c94ec9 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -328,13 +328,11 @@ var lowestCommonAncestor = function(root, p, q) { } if(root.val>p.val&&root.val>q.val) { // 向左子树查询 - let left = lowestCommonAncestor(root.left,p,q); - return left !== null&&left; + return root.left = lowestCommonAncestor(root.left,p,q); } if(root.val Date: Sun, 16 Oct 2022 10:46:42 +0800 Subject: [PATCH 09/33] =?UTF-8?q?Update=200239.=E6=BB=91=E5=8A=A8=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index b86fdd15..d41c092d 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -296,7 +296,7 @@ class Solution { ``` Python: -```python3 +```python from collections import deque From 819387081395ada6a866e5ce9ca236319cc2ca00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A7=E7=9C=BC=E7=9D=9B=E5=9B=BE=E5=9B=BE?= <108316255+L1Y1@users.noreply.github.com> Date: Sun, 16 Oct 2022 20:34:22 +0800 Subject: [PATCH 10/33] =?UTF-8?q?Update=200216.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8CIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 感觉这种解法更符合卡哥视频的讲解。 --- problems/0216.组合总和III.md | 35 +++++++++++++++++++------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 964facee..4273240c 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -397,24 +397,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){ * @return {number[][]} */ var combinationSum3 = function(k, n) { - const backtrack = (start) => { - const l = path.length; - if (l === k) { - const sum = path.reduce((a, b) => a + b); - if (sum === n) { - res.push([...path]); - } - return; + let res = []; + let path = []; + let sum = 0; + const dfs = (path,index) => { + // 剪枝操作 + if (sum > n){ + return } - for (let i = start; i <= 9 - (k - l) + 1; i++) { + if (path.length == k) { + if(sum == n){ + res.push([...path]); + return + } + } + for (let i = index; i <= 9 - (k-path.length) + 1;i++) { path.push(i); - backtrack(i + 1); - path.pop(); + sum = sum + i; + index += 1; + dfs(path,index); + sum -= i + path.pop() } } - let res = [], path = []; - backtrack(1); - return res; + dfs(path,1); + return res }; ``` From d874aaa2dd12685f54aba09201903319aa3bd183 Mon Sep 17 00:00:00 2001 From: Asterisk <44215173+casnz1601@users.noreply.github.com> Date: Sun, 16 Oct 2022 20:19:40 -0400 Subject: [PATCH 11/33] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 替代造成逻辑误导旧python代码 --- problems/0001.两数之和.md | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index acf2a995..7bada9af 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -152,25 +152,11 @@ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: records = dict() - # 用枚举更方便,就不需要通过索引再去取当前位置的值 - for idx, val in enumerate(nums): - if target - val not in records: - records[val] = idx - else: - return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引 -``` - -Python (v2): - -```python -class Solution: - def twoSum(self, nums: List[int], target: int) -> List[int]: - rec = {} - for i in range(len(nums)): - rest = target - nums[i] - # Use get to get the index of the data, making use of one of the dictionary properties. - if rec.get(rest, None) is not None: return [rec[rest], i] - rec[nums[i]] = i + for index, value in enumerate(nums): + if target - value in records: + return [records[target- value], index] + records[value] = index + return [] ``` Go: From f2ebe047dbd93a4e4c67fa5104d1bdfcbc49734a Mon Sep 17 00:00:00 2001 From: Allen <2439506288@qq.com> Date: Mon, 17 Oct 2022 08:36:45 +0800 Subject: [PATCH 12/33] =?UTF-8?q?=E4=BF=AE=E6=94=B9518=E9=A2=98=E7=9B=AE?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=EF=BC=8C=E6=9B=BF=E4=BB=A3=E8=BF=87=E6=97=B6?= =?UTF-8?q?=E7=9A=84=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0518.零钱兑换II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index e5c8b251..e29e2107 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -7,7 +7,7 @@ ## 518. 零钱兑换 II -[力扣题目链接](https://leetcode.cn/problems/coin-change-2/) +[力扣题目链接](https://leetcode.cn/problems/coin-change-ii/) 难度:中等 From 7a429700ae1bc4b5f99f0ee8fd9b510d5f13d9ba Mon Sep 17 00:00:00 2001 From: ckl <1051928078@qq.com> Date: Mon, 17 Oct 2022 20:16:55 +0800 Subject: [PATCH 13/33] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200052.N=E7=9A=87?= =?UTF-8?q?=E5=90=8EII.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0052.N皇后II.md | 49 +++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/problems/0052.N皇后II.md b/problems/0052.N皇后II.md index f1edd281..e4faac0c 100644 --- a/problems/0052.N皇后II.md +++ b/problems/0052.N皇后II.md @@ -256,7 +256,54 @@ int totalNQueens(int n){ return answer; } ``` - +Java +```java +class Solution { + int count = 0; + public int totalNQueens(int n) { + char[][] board = new char[n][n]; + for (char[] chars : board) { + Arrays.fill(chars, '.'); + } + backTrack(n, 0, board); + return count; + } + private void backTrack(int n, int row, char[][] board) { + if (row == n) { + count++; + return; + } + for (int col = 0; col < n; col++) { + if (isValid(row, col, n, board)) { + board[row][col] = 'Q'; + backTrack(n, row + 1, board); + board[row][col] = '.'; + } + } + } + private boolean isValid(int row, int col, int n, char[][] board) { + // 检查列 + for (int i = 0; i < row; ++i) { + if (board[i][col] == 'Q') { + return false; + } + } + // 检查45度对角线 + for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { + if (board[i][j] == 'Q') { + return false; + } + } + // 检查135度对角线 + for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) { + if (board[i][j] == 'Q') { + return false; + } + } + return true; + } +} +```

From 78db04b4b70d8cf879b2c7c9f2954f3465500ad0 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 18 Oct 2022 00:29:12 +0800 Subject: [PATCH 14/33] =?UTF-8?q?update=201002.=20=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 78eb1989..fd188660 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -451,6 +451,42 @@ object Solution { } } ``` + +Rust: + +```rust +impl Solution { + pub fn common_chars(words: Vec) -> Vec { + if words.is_empty() { + return vec![]; + } + let mut res = vec![]; + let mut hash = vec![0; 26]; + for i in words[0].bytes() { + hash[(i - b'a') as usize] += 1; + } + for i in words.iter().skip(1) { + let mut other_hash_str = vec![0; 26]; + for j in i.bytes() { + other_hash_str[(j - b'a') as usize] += 1; + } + for k in 0..26 { + hash[k] = hash[k].min(other_hash_str[k]); + } + } + + for (i, v) in hash.iter_mut().enumerate() { + while *v > 0 { + res.push(((i as u8 + b'a') as char).to_string()); + *v -= 1; + } + } + + res + } +} +``` +

From 1256daac2497ed11bf4e200e495b031ba2d1a03a Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 18 Oct 2022 00:51:19 +0800 Subject: [PATCH 15/33] =?UTF-8?q?update=200349.=E4=B8=A4=E4=B8=AA=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0349.两个数组的交集.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 153077ed..a6e07424 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -310,6 +310,22 @@ impl Solution { } ``` +解法2: + +```rust +use std::collections::HashSet; +impl Solution { + pub fn intersection(nums1: Vec, nums2: Vec) -> Vec { + nums1 + .into_iter() + .collect::>() + .intersection(&nums2.into_iter().collect::>()) + .copied() + .collect() + } +} +``` + C: ```C int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){ From 853243a20ed6d6afe9f5c5ad112d662f3d02eb65 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Tue, 18 Oct 2022 11:30:57 -0600 Subject: [PATCH 16/33] =?UTF-8?q?Update=200332.=E9=87=8D=E6=96=B0=E5=AE=89?= =?UTF-8?q?=E6=8E=92=E8=A1=8C=E7=A8=8B.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化了phython3的代码,把排序部分提前完成,避免重复排序 --- problems/0332.重新安排行程.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 90756d7d..84147532 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -355,16 +355,18 @@ class Solution: tickets_dict = defaultdict(list) for item in tickets: tickets_dict[item[0]].append(item[1]) + # 给每一个机场的到达机场排序,小的在前面,在回溯里首先被pop(0)出去 + # 这样最先找的的path就是排序最小的答案,直接返回 + for airport in tickets_dict: tickets_dict[airport].sort() ''' tickets_dict里面的内容是这样的 - {'JFK': ['SFO', 'ATL'], 'SFO': ['ATL'], 'ATL': ['JFK', 'SFO']}) + {'JFK': ['ATL', 'SFO'], 'SFO': ['ATL'], 'ATL': ['JFK', 'SFO']}) ''' path = ["JFK"] def backtracking(start_point): # 终止条件 if len(path) == len(tickets) + 1: return True - tickets_dict[start_point].sort() for _ in tickets_dict[start_point]: #必须及时删除,避免出现死循环 end_point = tickets_dict[start_point].pop(0) From 73e937f77fcf3e4deb752f6fe8960d009fdae944 Mon Sep 17 00:00:00 2001 From: tlylt Date: Wed, 19 Oct 2022 09:25:36 +0800 Subject: [PATCH 17/33] Update --- problems/0090.子集II.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index ea1eb4cd..9f935b60 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -261,7 +261,9 @@ class Solution: self.path.pop() ``` -### Python3 +### Python3 + +不使用used数组 ```python3 class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: @@ -288,6 +290,28 @@ class Solution: return res ``` +使用used数组 +```python3 +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + result = [] + path = [] + nums.sort() + used = [0] * len(nums) + def backtrack(nums, startIdx): + result.append(path[:]) + for i in range(startIdx, len(nums)): + if i > startIdx and nums[i] == nums[i-1] and used[i-1] == 0: + continue + used[i] = 1 + path.append(nums[i]) + backtrack(nums, i+1) + path.pop() + used[i] = 0 + backtrack(nums, 0) + return result +``` + ### Go ```Go @@ -526,7 +550,7 @@ func subsetsWithDup(_ nums: [Int]) -> [[Int]] { ### Scala -不使用userd数组: +不使用used数组: ```scala object Solution { From 9977fb5996d2e593d0bc220754d91c0abeec181f Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Wed, 19 Oct 2022 21:47:25 +0200 Subject: [PATCH 18/33] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20541.=20=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II=EF=BC=8C=20=E6=8F=90?= =?UTF-8?q?=E4=BE=9Bscala=E7=89=88=E6=9C=AC=E7=9A=84=E9=80=92=E5=BD=92?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 3dd6b1e8..02ad92a0 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -412,6 +412,26 @@ object Solution { } ``` +版本三: (递归) +```scala +import scala.annotation.tailrec + +object Solution { + def reverseStr(s: String, k: Int): String = { + @tailrec // 这个函数已经优化成了尾递归 + def reverse(s: String, needToReverse: Boolean, history: String): String = { + // 截取前k个字符(判断是否翻转) + val subStr = if (needToReverse) s.take(k).reverse else s.take(k) + // 如果字符串长度小于k,返回结果 + // 否则,对于剩余字符串进行同样的操作 + if (s.length < k) history + subStr + else reverse(s.drop(k), !needToReverse, history + subStr) + } + reverse(s, true, "") + } +} +``` + Rust: ```Rust From 77b431d27618a202d90b5bfc420b6686cbc66312 Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Wed, 19 Oct 2022 22:20:01 +0200 Subject: [PATCH 19/33] =?UTF-8?q?Update=200541.=E5=8F=8D=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 02ad92a0..f38ac042 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -399,14 +399,17 @@ object Solution { } } ``` -版本二: 首先利用sliding每隔k个进行分割,随后转换为数组,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String +版本二: 首先利用grouped每隔k个进行分割,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String ```scala -object Solution { +object SolutionFunc { def reverseStr(s: String, k: Int): String = { - s.sliding(k, k) - .toArray - .zipWithIndex - .map(v => if (v._2 % 2 == 0) v._1.reverse else v._1) + // s = "abcdefg", k = 2 + s.grouped(k) // Iterator ["ab", "cd", "ef", "g"] + .zipWithIndex // Iterator [("ab", 0), ("cd", 1), ("ef", 2), ("g", 3)] + .map { + case (subStr, index) => + if (index % 2 == 0) subStr.reverse else subStr + } .mkString } } From 7278b038c680d960d2c7d4858cb836144b90ea1c Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Wed, 19 Oct 2022 22:23:50 +0200 Subject: [PATCH 20/33] rename the object class name of Scala Solution 2 --- problems/0541.反转字符串II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index f38ac042..238e6349 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -401,7 +401,7 @@ object Solution { ``` 版本二: 首先利用grouped每隔k个进行分割,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String ```scala -object SolutionFunc { +object Solution { def reverseStr(s: String, k: Int): String = { // s = "abcdefg", k = 2 s.grouped(k) // Iterator ["ab", "cd", "ef", "g"] From 185e19748c7fadc5bade6ef6e775991e395ed7c9 Mon Sep 17 00:00:00 2001 From: vanyongqi <46806467+vanyongqi@users.noreply.github.com> Date: Thu, 20 Oct 2022 19:49:24 +0800 Subject: [PATCH 21/33] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加C语言版本,已通过Leetcode验证 --- ...0019.删除链表的倒数第N个节点.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 314c396e..b0641b5f 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -364,6 +364,40 @@ impl Solution { dummy_head.next } } +``` +C语言 +```c +/**c语言单链表的定义 + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { + //定义虚拟头节点dummy 并初始化使其指向head + struct ListNode* dummy = malloc(sizeof(struct ListNode)); + dummy->val = 0; + dummy->next = head; + //定义 fast slow 双指针 + struct ListNode* fast = head; + struct ListNode* slow = dummy; + + for (int i = 0; i < n; ++i) { + fast = fast->next; + } + while (fast) { + fast = fast->next; + slow = slow->next; + } + slow->next = slow->next->next;//删除倒数第n个节点 + head = dummy->next; + free(dummy);//删除虚拟节点dummy + return head; +} + + + ```

From 5dcdb06e64eef14bb555d6a0e9f8b9bfb90a4793 Mon Sep 17 00:00:00 2001 From: Guan-t7 Date: Thu, 20 Oct 2022 23:08:04 +0800 Subject: [PATCH 22/33] =?UTF-8?q?Update=200127.=E5=8D=95=E8=AF=8D=E6=8E=A5?= =?UTF-8?q?=E9=BE=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix typo --- problems/0127.单词接龙.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 4fa53046..2e30123d 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -31,7 +31,7 @@ # 思路 -以示例1为例,从这个图中可以看出 hit 到 cog的路线,不止一条,有三条,两条是最短的长度为5,一条长度为6。 +以示例1为例,从这个图中可以看出 hit 到 cog的路线,不止一条,有三条,一条是最短的长度为5,两条长度为6。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210827175432.png) From ec774357dd539e83a682ddc3733884cc369fcb04 Mon Sep 17 00:00:00 2001 From: lysice Date: Fri, 21 Oct 2022 17:19:29 +0800 Subject: [PATCH 23/33] =?UTF-8?q?[fix]=20=E9=94=99=E5=88=AB=E5=AD=97?= =?UTF-8?q?=E6=9B=B4=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 80c72305..2d556d8b 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -88,7 +88,7 @@ public: 对于窗口里的元素{2, 3, 5, 1 ,4},单调队列里只维护{5, 4} 就够了,保持单调队列里单调递减,此时队列出口元素就是窗口里最大元素。 -此时大家应该怀疑单调队列里维护着{5, 4} 怎么配合窗口经行滑动呢? +此时大家应该怀疑单调队列里维护着{5, 4} 怎么配合窗口进行滑动呢? 设计单调队列的时候,pop,和push操作要保持如下规则: From fddea62f38df395a6094f72f17a00fa831634821 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 22 Oct 2022 16:42:48 +0800 Subject: [PATCH 24/33] update 15.3sum about rust --- problems/0015.三数之和.md | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index fb289d54..5ee57127 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -655,7 +655,7 @@ impl Solution { ```Rust // 双指针法 -use std::collections::HashSet; +use std::cmp::Ordering; impl Solution { pub fn three_sum(nums: Vec) -> Vec> { let mut result: Vec> = Vec::new(); @@ -667,22 +667,21 @@ impl Solution { if i > 0 && nums[i] == nums[i - 1] { continue; } let (mut left, mut right) = (i + 1, len - 1); while left < right { - if nums[i] + nums[left] + nums[right] > 0 { - right -= 1; - // 去重 - while left < right && nums[right] == nums[right + 1] { right -= 1; } - } else if nums[i] + nums[left] + nums[right] < 0 { - left += 1; - // 去重 - while left < right && nums[left] == nums[left - 1] { left += 1; } - } else { - result.push(vec![nums[i], nums[left], nums[right]]); - // 去重 - right -= 1; - left += 1; - while left < right && nums[right] == nums[right + 1] { right -= 1; } - while left < right && nums[left] == nums[left - 1] { left += 1; } - } + match (nums[i] + nums[left] + nums[right]).cmp(&0){ + Ordering::Equal =>{ + result.push(vec![nums[i], nums[left], nums[right]]); + left +=1; + right -=1; + while left < right && nums[left] == nums[left - 1]{ + left += 1; + } + while left < right && nums[right] == nums[right+1]{ + right -= 1; + } + } + Ordering::Greater => right -= 1, + Ordering::Less => left += 1, + } } } result From 53793b70f9c9068bd45607d73465ed8256af30ac Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sat, 22 Oct 2022 21:55:08 +0800 Subject: [PATCH 25/33] update 18.4sum about rust --- problems/0018.四数之和.md | 36 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 463eaf8f..ca33eb57 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -527,6 +527,7 @@ public class Solution Rust: ```Rust +use std::cmp::Ordering; impl Solution { pub fn four_sum(nums: Vec, target: i32) -> Vec> { let mut result: Vec> = Vec::new(); @@ -545,22 +546,25 @@ impl Solution { if i > k + 1 && nums[i] == nums[i - 1] { continue; } let (mut left, mut right) = (i + 1, len - 1); while left < right { - if nums[k] + nums[i] > target - (nums[left] + nums[right]) { - right -= 1; - // 去重 - while left < right && nums[right] == nums[right + 1] { right -= 1; } - } else if nums[k] + nums[i] < target - (nums[left] + nums[right]) { - left += 1; - // 去重 - while left < right && nums[left] == nums[left - 1] { left += 1; } - } else { - result.push(vec![nums[k], nums[i], nums[left], nums[right]]); - // 去重 - while left < right && nums[right] == nums[right - 1] { right -= 1; } - while left < right && nums[left] == nums[left + 1] { left += 1; } - left += 1; - right -= 1; - } + match (nums[k] + nums[i] + nums[left] + nums[right]).cmp(&target){ + Ordering::Equal => { + result.push(vec![nums[k], nums[i], nums[left], nums[right]]); + left += 1; + right -= 1; + while left < right && nums[left] == nums[left - 1]{ + left += 1; + } + while left < right && nums[right] == nums[right + 1]{ + right -= 1; + } + } + Ordering::Less => { + left +=1; + }, + Ordering::Greater => { + right -= 1; + } + } } } } From 8f7f6185db0ed11af2ceb447ec0f1c84664dc359 Mon Sep 17 00:00:00 2001 From: pwq <57176977+pvvq@users.noreply.github.com> Date: Tue, 25 Oct 2022 01:10:21 +0800 Subject: [PATCH 26/33] 0349 fix code block language change language from `c++` to `CPP`, since `c++` doesn't get rendered as expected (here)[https://programmercarl.com/0349.%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86.html#%E5%90%8E%E8%AE%B0]. --- problems/0349.两个数组的交集.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index a6e07424..bd83fae9 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -91,7 +91,7 @@ public: 对应C++代码如下: -```c++ +```CPP class Solution { public: vector intersection(vector& nums1, vector& nums2) { From 84b4f2674436910c87e258b5984b1404591bc060 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 25 Oct 2022 22:17:21 +0800 Subject: [PATCH 27/33] =?UTF-8?q?update=2028.=E6=89=BE=E5=87=BA=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=E9=A1=B9=E7=9A=84=E4=B8=8B=E6=A0=87=20about?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 7078738e..697e8c2d 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1299,6 +1299,53 @@ impl Solution { } ``` +> 前缀表统一减一 + +```rust +impl Solution { + pub fn get_next(mut next: Vec, s: &Vec) -> Vec { + let mut j = -1; + for i in 1..s.len() { + while j >= 0 && s[(j + 1) as usize] != s[i] { + j = next[j as usize]; + } + if s[i] == s[(j + 1) as usize] { + j += 1; + } + next[i] = j; + } + next + } + pub fn str_str(haystack: String, needle: String) -> i32 { + if needle.is_empty() { + return 0; + } + if haystack.len() < needle.len() { + return -1; + } + let (haystack_chars, needle_chars) = ( + haystack.chars().collect::>(), + needle.chars().collect::>(), + ); + let mut j = -1; + let mut next = vec![-1; needle.len()]; + next = Self::get_next(next, &needle_chars); + for (i, v) in haystack_chars.into_iter().enumerate() { + while j >= 0 && v != needle_chars[(j + 1) as usize] { + j = next[j as usize]; + } + if v == needle_chars[(j + 1) as usize] { + j += 1; + } + if j == needle_chars.len() as i32 - 1 { + return (i - needle_chars.len() + 1) as i32; + } + } + -1 + } +} +``` +

From a582640c7a800cbce116f1cd6475a0a68a629ff3 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 25 Oct 2022 22:35:54 +0800 Subject: [PATCH 28/33] =?UTF-8?q?Update=200028.=E5=AE=9E=E7=8E=B0strStr.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 697e8c2d..19d16e9f 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -1303,7 +1303,8 @@ impl Solution { ```rust impl Solution { - pub fn get_next(mut next: Vec, s: &Vec) -> Vec { + pub fn get_next(next_len: usize, s: &Vec) -> Vec { + let mut next = vec![-1; next_len]; let mut j = -1; for i in 1..s.len() { while j >= 0 && s[(j + 1) as usize] != s[i] { @@ -1328,8 +1329,7 @@ impl Solution { needle.chars().collect::>(), ); let mut j = -1; - let mut next = vec![-1; needle.len()]; - next = Self::get_next(next, &needle_chars); + let next = Self::get_next(needle.len(), &needle_chars); for (i, v) in haystack_chars.into_iter().enumerate() { while j >= 0 && v != needle_chars[(j + 1) as usize] { j = next[j as usize]; From 856907e3d596f6796b4817aa6b80a26e6dbb73d6 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 25 Oct 2022 23:26:04 +0800 Subject: [PATCH 29/33] =?UTF-8?q?update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2.md=20about=20rust=20?= =?UTF-8?q?=E5=89=8D=E7=BC=80=E8=A1=A8=E7=BB=9F=E4=B8=80=20-1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 18de79d5..378d1a63 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -615,6 +615,35 @@ impl Solution { } ``` +>前缀表统一减一 + +```rust + pub fn get_next(next_len: usize, s: &Vec) -> Vec { + let mut next = vec![-1; next_len]; + let mut j = -1; + for i in 1..s.len() { + while j >= 0 && s[i] != s[(j + 1) as usize] { + j = next[j as usize]; + } + if s[i] == s[(j + 1) as usize] { + j += 1; + } + next[i] = j; + } + next + } + pub fn repeated_substring_pattern(s: String) -> bool { + let s_chars = s.chars().collect::>(); + let next = Self::get_next(s_chars.len(), &s_chars); + if next[s_chars.len() - 1] >= 0 + && s_chars.len() % (s_chars.len() - (next[s_chars.len() - 1] + 1) as usize) == 0 + { + return true; + } + false + } +``` +

From f386e3ca68c602c84f875ab1b6538a41e000459b Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Tue, 25 Oct 2022 23:27:09 +0800 Subject: [PATCH 30/33] =?UTF-8?q?Update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=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/0459.重复的子字符串.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 378d1a63..b7d86880 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -618,6 +618,7 @@ impl Solution { >前缀表统一减一 ```rust +impl Solution { pub fn get_next(next_len: usize, s: &Vec) -> Vec { let mut next = vec![-1; next_len]; let mut j = -1; @@ -642,6 +643,7 @@ impl Solution { } false } +} ``` From 1204f0e4ed06d11d5e55ad47d94fc71733bf7ce5 Mon Sep 17 00:00:00 2001 From: Liu YongLiang <41845017+tlylt@users.noreply.github.com> Date: Wed, 26 Oct 2022 20:30:32 +0800 Subject: [PATCH 31/33] =?UTF-8?q?Update=201221.=E5=88=86=E5=89=B2=E5=B9=B3?= =?UTF-8?q?=E8=A1=A1=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/1221.分割平衡字符串.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/1221.分割平衡字符串.md b/problems/1221.分割平衡字符串.md index 94d7bca8..b587514a 100644 --- a/problems/1221.分割平衡字符串.md +++ b/problems/1221.分割平衡字符串.md @@ -117,7 +117,7 @@ class Solution: diff -= 1 else: diff += 1 - if tilt == 0: + if diff == 0: ans += 1 return ans ``` From 448ef5f40618d2f7428e6ea7107f2f9f24fe987c Mon Sep 17 00:00:00 2001 From: xiaoyu2018 <861900161@qq.com> Date: Fri, 28 Oct 2022 10:57:36 +0800 Subject: [PATCH 32/33] update 0121 and 0122 --- problems/0121.买卖股票的最佳时机.md | 42 +++++++++++++++++++ ...票的最佳时机II(动态规划).md | 42 +++++++++++++++++-- 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 790bbd88..63ac5d04 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -464,6 +464,47 @@ function maxProfit(prices: number[]): number { }; ``` +C#: + +> 贪心法 + +```csharp +public class Solution +{ + public int MaxProfit(int[] prices) + { + int min = Int32.MaxValue; + int res = 0; + for (int i = 0; i < prices.Length; i++) + { + min = Math.Min(prices[i], min); + res = Math.Max(prices[i] - min, res); + } + return res; + } +} +``` + +> 动态规划 + +```csharp +public class Solution +{ + public int MaxProfit(int[] prices) + { + int[] dp = new int[2]; + int size = prices.Length; + (dp[0], dp[1]) = (-prices[0], 0); + for (int i = 0; i < size; i++) + { + dp[0] = Math.Max(dp[0], -prices[i]); + dp[1] = Math.Max(dp[1], dp[0]+prices[i]); + } + return dp[1]; + } +} +``` + @@ -471,3 +512,4 @@ function maxProfit(prices: number[]): number { + diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index f5f3f720..f2aec68b 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -169,8 +169,6 @@ class Solution { } ``` - - Python: > 版本一: @@ -253,8 +251,6 @@ func max(a,b int)int{ } ``` - - Javascript: ```javascript // 方法一:动态规划(dp 数组) @@ -331,9 +327,47 @@ function maxProfit(prices: number[]): number { }; ``` +C#: + +> 贪心法 + +```csharp +public class Solution +{ + public int MaxProfit(int[] prices) + { + int res = 0; + for (int i = 1; i < prices.Length; i++) + res += Math.Max(0, prices[i] - prices[i-1]); + return res; + } +} +``` + +> 动态规划 + +```csharp +public class Solution +{ + public int MaxProfit(int[] prices) + { + int[] dp = new int[2]; + dp[0] = -prices[0]; + + for (int i = 1; i < prices.Length; i++) + { + dp[0] = dp[0]>dp[1] - prices[i]?dp[0]:dp[1] - prices[i]; + dp[1] = dp[1] > dp[0] + prices[i] ? dp[1] : dp[0] + prices[i]; + } + return dp[1]; + } +} +``` +

+ From 924f5b105d8ba42cdef159570356eb40deb4a375 Mon Sep 17 00:00:00 2001 From: Peilin Sun <46664832+PPPerry@users.noreply.github.com> Date: Fri, 28 Oct 2022 20:53:21 +0800 Subject: [PATCH 33/33] =?UTF-8?q?Update=20=E6=A0=88=E4=B8=8E=E9=98=9F?= =?UTF-8?q?=E5=88=97=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 da3a6dfa..66b86919 100644 --- a/problems/栈与队列理论基础.md +++ b/problems/栈与队列理论基础.md @@ -59,7 +59,7 @@ C++标准库是有多个版本的,要知道我们使用的STL是哪个版本 ![栈与队列理论3](https://img-blog.csdnimg.cn/20210104235459376.png) -**我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的低层结构。** +**我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。** deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。