From 31c9f09776b9ef6bf9e7861a32a43fde571fdcbf Mon Sep 17 00:00:00 2001 From: reoooh Date: Wed, 28 Jul 2021 23:57:26 +0800 Subject: [PATCH 01/25] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=20Ruby=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 42 ++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index cce471ae..66be52a0 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -235,8 +235,6 @@ class Solution: return -1 ``` - - **Go:** (版本一)左闭右闭区间 @@ -279,7 +277,7 @@ func search(nums []int, target int) int { } ``` -**javaScript:** +**JavaScript:** ```js @@ -316,7 +314,45 @@ var search = function(nums, target) { ``` +**Ruby:** +```ruby +# (版本一)左闭右闭区间 + +def search(nums, target) + left, right = 0, nums.length - 1 + while left <= right # 由于定义target在一个在左闭右闭的区间里,因此极限情况下存在left==right + middle = (left + right) / 2 + if nums[middle] > target + right = middle - 1 + elsif nums[middle] < target + left = middle + 1 + else + return middle # return兼具返回与跳出循环的作用 + end + end + -1 +end + +# (版本二)左闭右开区间 + +def search(nums, target) + left, right = 0, nums.length - 1 + while left < right # 由于定义target在一个在左闭右开的区间里,因此极限情况下right=left+1 + middle = (left + right) / 2 + if nums[middle] > target + right = middle + elsif nums[middle] < target + left = middle + 1 + else + return middle + end + end + -1 +end + +p search(nums,target) +``` From 4fcb27c7cf827d0c13bc261c4374cb5b199cbf1d Mon Sep 17 00:00:00 2001 From: reoooh Date: Thu, 29 Jul 2021 00:07:44 +0800 Subject: [PATCH 02/25] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=20Ruby=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 66be52a0..caec38b1 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -337,7 +337,7 @@ end # (版本二)左闭右开区间 def search(nums, target) - left, right = 0, nums.length - 1 + left, right = 0, nums.length while left < right # 由于定义target在一个在左闭右开的区间里,因此极限情况下right=left+1 middle = (left + right) / 2 if nums[middle] > target From 7029cf6b6eb760df09d39ce9a399f34016682ccf Mon Sep 17 00:00:00 2001 From: reoooh Date: Thu, 29 Jul 2021 13:49:02 +0800 Subject: [PATCH 03/25] =?UTF-8?q?=E6=B7=BB=E5=8A=A00704=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=20Ruby=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index caec38b1..ed0e2eed 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -350,8 +350,6 @@ def search(nums, target) end -1 end - -p search(nums,target) ``` From e9c5f17af52cbeee408e349d7a7655b5d711bc80 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 18:48:56 +0800 Subject: [PATCH 04/25] =?UTF-8?q?724.=E5=AF=BB=E6=89=BE=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E4=B8=AD=E5=BF=83=E4=B8=8B=E6=A0=87=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0724.寻找数组的中心索引.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/problems/0724.寻找数组的中心索引.md b/problems/0724.寻找数组的中心索引.md index bf989979..09966e05 100644 --- a/problems/0724.寻找数组的中心索引.md +++ b/problems/0724.寻找数组的中心索引.md @@ -67,6 +67,24 @@ public: ## Java ```java +class Solution { + public int pivotIndex(int[] nums) { + int sum = 0; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; // 总和 + } + int leftSum = 0; + int rightSum = 0; + for (int i = 0; i < nums.length; i++) { + leftSum += nums[i]; + rightSum = sum - leftSum + nums[i]; // leftSum 里面已经有 nums[i],多减了一次,所以加上 + if (leftSum == rightSum) { + return i; + } + } + return -1; // 不存在 + } +} ``` ## Python @@ -90,4 +108,3 @@ public: * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
- From 3fd951ef5fec91b3dc9be7e57aa76daf83c35f87 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 18:56:15 +0800 Subject: [PATCH 05/25] =?UTF-8?q?922.=20=E6=8C=89=E5=A5=87=E5=81=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84II=20=E6=B7=BB=E5=8A=A0Java?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0922.按奇偶排序数组II.md | 26 +++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index bb609c12..d4c1be7a 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -120,6 +120,31 @@ public: ## Java ```java +// 方法一 +class Solution { + public int[] sortArrayByParityII(int[] nums) { + // 分别存放 nums 中的奇数、偶数 + int len = nums.length; + int evenIndex = 0; + int oddIndex = 0; + int[] even = new int[len / 2]; + int[] odd = new int[len / 2]; + for (int i = 0; i < len; i++) { + if (nums[i] % 2 == 0) { + even[evenIndex++] = nums[i]; + } else { + odd[oddIndex++] = nums[i]; + } + } + // 把奇偶数组重新存回 nums + int index = 0; + for (int i = 0; i < even.length; i++) { + nums[index++] = even[i]; + nums[index++] = odd[i]; + } + return nums; + } +} ``` ## Python @@ -143,4 +168,3 @@ public: * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
- From d8247fe8499f14497972fc32456f752a7bf6d574 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 19:22:47 +0800 Subject: [PATCH 06/25] =?UTF-8?q?844.=E6=AF=94=E8=BE=83=E5=90=AB=E9=80=80?= =?UTF-8?q?=E6=A0=BC=E7=9A=84=E5=AD=97=E7=AC=A6=E4=B8=B2=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0844.比较含退格的字符串.md | 28 +++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 9f37959d..4b4ff63b 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -14,7 +14,7 @@ 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。 注意:如果对空文本输入退格字符,文本继续为空。 -  + 示例 1: * 输入:S = "ab#c", T = "ad#c" * 输出:true @@ -160,6 +160,32 @@ public: Java: +```java +// 普通方法(使用栈的思路) +class Solution { + public boolean backspaceCompare(String s, String t) { + StringBuilder ssb = new StringBuilder(); // 模拟栈 + StringBuilder tsb = new StringBuilder(); // 模拟栈 + // 分别处理两个 String + for (char c : s.toCharArray()) { + if (c != '#') { + ssb.append(c); // 模拟入栈 + } else if (ssb.length() > 0){ // 栈非空才能弹栈 + ssb.deleteCharAt(ssb.length() - 1); // 模拟弹栈 + } + } + for (char c : t.toCharArray()) { + if (c != '#') { + tsb.append(c); // 模拟入栈 + } else if (tsb.length() > 0){ // 栈非空才能弹栈 + tsb.deleteCharAt(tsb.length() - 1); // 模拟弹栈 + } + } + return ssb.toString().equals(tsb.toString()); + } +} +``` + Python: Go: From a6a8650b8a6524ed03cf599f1c32fc42c78cd8e5 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 19:32:33 +0800 Subject: [PATCH 07/25] =?UTF-8?q?205.=E5=90=8C=E6=9E=84=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0205.同构字符串.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0205.同构字符串.md b/problems/0205.同构字符串.md index 4e963ece..06ea5701 100644 --- a/problems/0205.同构字符串.md +++ b/problems/0205.同构字符串.md @@ -68,6 +68,25 @@ public: ## Java ```java +class Solution { + public boolean isIsomorphic(String s, String t) { + Map map1 = new HashMap<>(); + Map map2 = new HashMap<>(); + for (int i = 0, j = 0; i < s.length(); i++, j++) { + if (!map1.containsKey(s.charAt(i))) { + map1.put(s.charAt(i), t.charAt(j)); // map1保存 s[i] 到 t[j]的映射 + } + if (!map2.containsKey(t.charAt(j))) { + map2.put(t.charAt(j), s.charAt(i)); // map1保存 t[j] 到 s[i]的映射 + } + // 无法映射,返回 false + if (map1.get(s.charAt(i)) != t.charAt(j) || map2.get(t.charAt(j)) != s.charAt(i)) { + return false; + } + } + return true; + } +} ``` ## Python From 9e08c0e5de17773b345f0cc59fb661b333bd946f Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 19:36:37 +0800 Subject: [PATCH 08/25] =?UTF-8?q?205.=E5=90=8C=E6=9E=84=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC=EF=BC=88?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=E4=BF=AE=E6=94=B9=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0205.同构字符串.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0205.同构字符串.md b/problems/0205.同构字符串.md index 06ea5701..7ffa3fbf 100644 --- a/problems/0205.同构字符串.md +++ b/problems/0205.同构字符串.md @@ -77,7 +77,7 @@ class Solution { map1.put(s.charAt(i), t.charAt(j)); // map1保存 s[i] 到 t[j]的映射 } if (!map2.containsKey(t.charAt(j))) { - map2.put(t.charAt(j), s.charAt(i)); // map1保存 t[j] 到 s[i]的映射 + map2.put(t.charAt(j), s.charAt(i)); // map2保存 t[j] 到 s[i]的映射 } // 无法映射,返回 false if (map1.get(s.charAt(i)) != t.charAt(j) || map2.get(t.charAt(j)) != s.charAt(i)) { From 1521e4016537243bd2a6d5898f2099e53f588d42 Mon Sep 17 00:00:00 2001 From: posper Date: Thu, 29 Jul 2021 20:00:16 +0800 Subject: [PATCH 09/25] =?UTF-8?q?31.=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=8E=92?= =?UTF-8?q?=E5=88=97=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0031.下一个排列.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index fbe31eb3..53e6644d 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -99,6 +99,24 @@ public: ## Java ```java +class Solution { + public void nextPermutation(int[] nums) { + for (int i = nums.length - 1; i >= 0; i--) { + for (int j = nums.length - 1; j > i; j--) { + if (nums[j] > nums[i]) { + // 交换 + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + // [i + 1, nums.length) 内元素升序排序 + Arrays.sort(nums, i + 1, nums.length); + return; + } + } + } + Arrays.sort(nums); // 不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 + } +} ``` ## Python From 0b2312ffec67c90a53feb938a6df5444c41fbc1a Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 09:02:15 -0400 Subject: [PATCH 10/25] =?UTF-8?q?Update=200404.=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?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 添加python3 迭代方法的代码. Q: 我为什么要更改当前已有的递归代码? A: 因为我发现当前版本的递归代码跟Carl哥的逻辑不是特别一样. 我承认解题思路千变万化, 但是个人感觉最好最好还是尽量跟Carl的思路一样, 这样方便初学者阅读不同语言编写出来的代码. --- problems/0404.左叶子之和.md | 56 +++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index aa758367..2a76a461 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -205,25 +205,51 @@ class Solution { Python: -```Python + **递归** -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right +```python class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: - self.res=0 - def areleftleaves(root): - if not root:return - if root.left and (not root.left.left) and (not root.left.right):self.res+=root.left.val - areleftleaves(root.left) - areleftleaves(root.right) - areleftleaves(root) - return self.res + if not root: + return 0 + + left_left_leaves_sum = self.sumOfLeftLeaves(root.left) # 左 + right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右 + + cur_left_leaf_val = 0 + if root.left and not root.left.left and not root.left.right: + cur_left_leaf_val = root.left.val # 中 + + return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum ``` + +**迭代** +```python +class Solution: + def sumOfLeftLeaves(self, root: TreeNode) -> int: + """ + Idea: Each time check current node's left node. + If current node don't have one, skip it. + """ + stack = [] + if root: + stack.append(root) + res = 0 + + while stack: + # 每次都把当前节点的左节点加进去. + cur_node = stack.pop() + if cur_node.left and not cur_node.left.left and not cur_node.left.right: + res += cur_node.left.val + + if cur_node.left: + stack.append(cur_node.left) + if cur_node.right: + stack.append(cur_node.right) + + return res +``` + Go: > 递归法 From 2f412e5c7d3b41b66946d92e699330cb7e5e5036 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 11:18:26 -0400 Subject: [PATCH 11/25] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20513.=E6=89=BE?= =?UTF-8?q?=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC=20python?= =?UTF-8?q?=20=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 更改python 递归代码: 上一版本python代码跟卡哥思路不一样, 感觉把不同的解题方法放在这里不方便初学者学习. 所以建议更改. 2. 添加迭代方法代码. --- problems/0513.找树左下角的值.md | 61 +++++++++++++++++++++----- 1 file changed, 49 insertions(+), 12 deletions(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 17d15fde..391118ab 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -274,8 +274,9 @@ class Solution { Python: + +**递归法 - 回溯** ```python -//递归法 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): @@ -284,17 +285,53 @@ Python: # self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: - depth=0 - self.res=[] - def level(root,depth): - if not root:return - if depth==len(self.res): - self.res.append([]) - self.res[depth].append(root.val) - level(root.left,depth+1) - level(root.right,depth+1) - level(root,depth) - return self.res[-1][0] + max_depth = -float("INF") + max_left_value = -float("INF") + + def __traversal(root, left_len): + nonlocal max_depth, max_left_value + + if not root.left and not root.right: + if left_len > max_depth: + max_depth = left_len + max_left_value = root.val + return + + if root.left: + left_len += 1 + __traversal(root.left, left_len) + left_len -= 1 + + if root.right: + left_len += 1 + __traversal(root.right, left_len) + left_len -= 1 + return + + __traversal(root, 0) + + return max_left_value +``` + +**迭代法 - 层序遍历** +```python +class Solution: + def findBottomLeftValue(self, root: TreeNode) -> int: + queue = deque() + if root: + queue.append(root) + result = 0 + while queue: + q_len = len(queue) + for i in range(q_len): + if i == 0: + result = queue[i].val + cur = queue.popleft() + if cur.left: + queue.append(cur.left) + if cur.right: + queue.append(cur.right) + return result ``` Go: From 8c53c48ea87fc2f02934799da6f659a7647eb268 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 11:21:14 -0400 Subject: [PATCH 12/25] =?UTF-8?q?Revert=20"=E6=9B=B4=E6=96=B0=20513.?= =?UTF-8?q?=E6=89=BE=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC?= =?UTF-8?q?=20python=20=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 2f412e5c7d3b41b66946d92e699330cb7e5e5036. --- problems/0513.找树左下角的值.md | 61 +++++--------------------- 1 file changed, 12 insertions(+), 49 deletions(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 391118ab..17d15fde 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -274,9 +274,8 @@ class Solution { Python: - -**递归法 - 回溯** ```python +//递归法 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): @@ -285,53 +284,17 @@ Python: # self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: - max_depth = -float("INF") - max_left_value = -float("INF") - - def __traversal(root, left_len): - nonlocal max_depth, max_left_value - - if not root.left and not root.right: - if left_len > max_depth: - max_depth = left_len - max_left_value = root.val - return - - if root.left: - left_len += 1 - __traversal(root.left, left_len) - left_len -= 1 - - if root.right: - left_len += 1 - __traversal(root.right, left_len) - left_len -= 1 - return - - __traversal(root, 0) - - return max_left_value -``` - -**迭代法 - 层序遍历** -```python -class Solution: - def findBottomLeftValue(self, root: TreeNode) -> int: - queue = deque() - if root: - queue.append(root) - result = 0 - while queue: - q_len = len(queue) - for i in range(q_len): - if i == 0: - result = queue[i].val - cur = queue.popleft() - if cur.left: - queue.append(cur.left) - if cur.right: - queue.append(cur.right) - return result + depth=0 + self.res=[] + def level(root,depth): + if not root:return + if depth==len(self.res): + self.res.append([]) + self.res[depth].append(root.val) + level(root.left,depth+1) + level(root.right,depth+1) + level(root,depth) + return self.res[-1][0] ``` Go: From 49d55fb1c8c26f668c1676075ac10a21b527ab92 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 11:25:33 -0400 Subject: [PATCH 13/25] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20513.=E6=89=BE?= =?UTF-8?q?=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC=20python?= =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 上一版本 递归python代码跟题解的方式不同. 个人认为不同方法做出的代码没有必要放在题解里, 建议修改成我提供的python版本. 2. 增加Python3 迭代部分的代码. --- problems/0513.找树左下角的值.md | 66 +++++++++++++++++++------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 17d15fde..e83fcc18 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -274,27 +274,57 @@ class Solution { Python: + +**递归 - 回溯** ```python -//递归法 -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: - depth=0 - self.res=[] - def level(root,depth): - if not root:return - if depth==len(self.res): - self.res.append([]) - self.res[depth].append(root.val) - level(root.left,depth+1) - level(root.right,depth+1) - level(root,depth) - return self.res[-1][0] + max_depth = -float("INF") + max_left_value = -float("INF") + + def __traversal(root, left_len): + nonlocal max_depth, max_left_value + + if not root.left and not root.right: + if left_len > max_depth: + max_depth = left_len + max_left_value = root.val + return + + if root.left: + left_len += 1 + __traversal(root.left, left_len) + left_len -= 1 + + if root.right: + left_len += 1 + __traversal(root.right, left_len) + left_len -= 1 + return + + __traversal(root, 0) + + return max_left_value +``` +**迭代 - 层序遍历** +```python +class Solution: + def findBottomLeftValue(self, root: TreeNode) -> int: + queue = deque() + if root: + queue.append(root) + result = 0 + while queue: + q_len = len(queue) + for i in range(q_len): + if i == 0: + result = queue[i].val + cur = queue.popleft() + if cur.left: + queue.append(cur.left) + if cur.right: + queue.append(cur.right) + return result ``` Go: From 1dd4a529fcc7e7d9fb2de170fbd628d9f2af6f7f Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 13:50:56 -0400 Subject: [PATCH 14/25] =?UTF-8?q?Update=200513.=E6=89=BE=E6=A0=91=E5=B7=A6?= =?UTF-8?q?=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更改变量名称 --- problems/0513.找树左下角的值.md | 34 +++++++++++--------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index e83fcc18..27c6e83c 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -280,31 +280,25 @@ Python: class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: max_depth = -float("INF") - max_left_value = -float("INF") - - def __traversal(root, left_len): - nonlocal max_depth, max_left_value + leftmost_val = 0 + def __traverse(root, cur_depth): + nonlocal max_depth, leftmost_val if not root.left and not root.right: - if left_len > max_depth: - max_depth = left_len - max_left_value = root.val - return - + if cur_depth > max_depth: + max_depth = cur_depth + leftmost_val = root.val if root.left: - left_len += 1 - __traversal(root.left, left_len) - left_len -= 1 - + cur_depth += 1 + __traverse(root.left, cur_depth) + cur_depth -= 1 if root.right: - left_len += 1 - __traversal(root.right, left_len) - left_len -= 1 - return - - __traversal(root, 0) + cur_depth += 1 + __traverse(root.right, cur_depth) + cur_depth -= 1 - return max_left_value + __traverse(root, 0) + return leftmost_val ``` **迭代 - 层序遍历** ```python From 440e04fffe7bc5cfacd11653fc6f0d3704382767 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Thu, 29 Jul 2021 15:50:46 -0400 Subject: [PATCH 15/25] =?UTF-8?q?=E6=9B=B4=E6=94=B9=200112.=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=80=BB=E5=92=8C.md=20Python3=20=E4=BB=A3=E7=A0=81.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0112.路径总和: 1. 修改了 python3 注释, 更改代码格式. 2. 增加了迭代方法Python3代码. 0113.路径总和-ii: 上一版python3代码的问题: (1)注释一般不用// (2)代码格式有些不规范. (3)内层函数命名也不是特别的informative. 新版本代码修改了上述问题. 本次提交代码均已通过leetcode测试. --- problems/0112.路径总和.md | 113 ++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 41 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index ae9a9267..474e17da 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -416,6 +416,8 @@ class Solution { Python: 0112.路径总和 + +**递归** ```python # Definition for a binary tree node. # class TreeNode: @@ -424,28 +426,56 @@ Python: # self.left = left # self.right = right -// 递归法 - class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: - def isornot(root,targetSum)->bool: - if (not root.left) and (not root.right) and targetSum == 0:return True // 遇到叶子节点,并且计数为0 - if (not root.left) and (not root.right):return False //遇到叶子节点,计数不为0 + def isornot(root, targetSum) -> bool: + if (not root.left) and (not root.right) and targetSum == 0: + return True # 遇到叶子节点,并且计数为0 + if (not root.left) and (not root.right): + return False # 遇到叶子节点,计数不为0 if root.left: - targetSum -= root.left.val //左节点 - if isornot(root.left,targetSum):return True //递归,处理左节点 - targetSum += root.left.val //回溯 + targetSum -= root.left.val # 左节点 + if isornot(root.left, targetSum): return True # 递归,处理左节点 + targetSum += root.left.val # 回溯 if root.right: - targetSum -= root.right.val //右节点 - if isornot(root.right,targetSum):return True //递归,处理右节点 - targetSum += root.right.val //回溯 + targetSum -= root.right.val # 右节点 + if isornot(root.right, targetSum): return True # 递归,处理右节点 + targetSum += root.right.val # 回溯 return False - - if root == None:return False //别忘记处理空TreeNode - else:return isornot(root,targetSum-root.val) + + if root == None: + return False # 别忘记处理空TreeNode + else: + return isornot(root, targetSum - root.val) ``` +**迭代 - 层序遍历** +```python +class Solution: + def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: + if not root: + return False + + stack = [] # [(当前节点,路径数值), ...] + stack.append((root, root.val)) + + while stack: + cur_node, path_sum = stack.pop() + + if not cur_node.left and not cur_node.right and path_sum == targetSum: + return True + + if cur_node.right: + stack.append((cur_node.right, path_sum + cur_node.right.val)) + + if cur_node.left: + stack.append((cur_node.left, path_sum + cur_node.left.val)) + + return False +``` 0113.路径总和-ii + +**递归** ```python # Definition for a binary tree node. # class TreeNode: @@ -453,35 +483,36 @@ class Solution: # self.val = val # self.left = left # self.right = right -//递归法 class Solution: def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: - path=[] - res=[] - def pathes(root,targetSum): - if (not root.left) and (not root.right) and targetSum == 0: // 遇到叶子节点,并且计数为0 - res.append(path[:]) //找到一种路径,记录到res中,注意必须是path[:]而不是path - return - if (not root.left) and (not root.right):return // 遇到叶子节点直接返回 - if root.left: //左 - targetSum -= root.left.val - path.append(root.left.val) //递归前记录节点 - pathes(root.left,targetSum) //递归 - targetSum += root.left.val //回溯 - path.pop() //回溯 - if root.right: //右 - targetSum -= root.right.val - path.append(root.right.val) //递归前记录节点 - pathes(root.right,targetSum) //递归 - targetSum += root.right.val //回溯 - path.pop() //回溯 - return - - if root == None:return [] //处理空TreeNode - else: - path.append(root.val) //首先处理根节点 - pathes(root,targetSum-root.val) - return res + + def traversal(cur_node, remain): + if not cur_node.left and not cur_node.right and remain == 0: + result.append(path[:]) + return + + if not cur_node.left and not cur_node.right: return + + if cur_node.left: + path.append(cur_node.left.val) + remain -= cur_node.left.val + traversal(cur_node.left, remain) + path.pop() + remain += cur_node.left.val + + if cur_node.right: + path.append(cur_node.right.val) + remain -= cur_node.right.val + traversal(cur_node.right, remain) + path.pop() + remain += cur_node.right.val + + result, path = [], [] + if not root: + return [] + path.append(root.val) + traversal(root, targetSum - root.val) + return result ``` Go: From 2119e411b73d818baaec8ca8140c7b619358bd54 Mon Sep 17 00:00:00 2001 From: xsduan98 Date: Fri, 30 Jul 2021 18:21:18 +0800 Subject: [PATCH 16/25] =?UTF-8?q?657.=20=E6=9C=BA=E5=99=A8=E4=BA=BA?= =?UTF-8?q?=E8=83=BD=E5=90=A6=E8=BF=94=E5=9B=9E=E5=8E=9F=E7=82=B9=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0657.机器人能否返回原点.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index cd26836c..b1fb6f21 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -71,6 +71,21 @@ public: ## Java ```java +// 时间复杂度:O(n) +// 空间复杂度:如果采用 toCharArray,则是 O(n);如果使用 charAt,则是 O(1) +class Solution { + public boolean judgeCircle(String moves) { + int x = 0; + int y = 0; + for (char c : moves.toCharArray()) { + if (c == 'U') y++; + if (c == 'D') y--; + if (c == 'L') x++; + if (c == 'R') x--; + } + return x == 0 && y == 0; + } +} ``` ## Python From 58ed197ba94f17646969ddf0e45ed851f5b03961 Mon Sep 17 00:00:00 2001 From: xsduan98 Date: Fri, 30 Jul 2021 18:54:43 +0800 Subject: [PATCH 17/25] =?UTF-8?q?1365.=E6=9C=89=E5=A4=9A=E5=B0=91=E5=B0=8F?= =?UTF-8?q?=E4=BA=8E=E5=BD=93=E5=89=8D=E6=95=B0=E5=AD=97=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E5=AD=97=20=E6=B7=BB=E5=8A=A0Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...据数字二进制下1的数目排序.md | 48 +++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index e464f716..a3d724fa 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -16,7 +16,7 @@ 换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。 以数组形式返回答案。 -  + 示例 1: 输入:nums = [8,1,2,2,3] @@ -35,7 +35,7 @@ 示例 3: 输入:nums = [7,7,7,7] 输出:[0,0,0,0] -  + 提示: * 2 <= nums.length <= 500 * 0 <= nums[i] <= 100 @@ -120,8 +120,51 @@ public: ## Java ```java +/** +* 解法一:暴力 +* 时间复杂度:O(n^2) +* 空间复杂度:O(n) +*/ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + for (int j = 0; j < nums.length; j++) { + if (nums[j] < nums[i] && j != i) { // 注意 j 不能和 i 重合 + res[i]++; + } + } + } + return res; + } +} ``` +```java +/** +* 优化:排序 + 哈希表 +* 时间复杂度:O(nlogn) +* 空间复杂度:O(n) +*/ +class Solution { + public int[] smallerNumbersThanCurrent(int[] nums) { + int[] res = Arrays.copyOf(nums, nums.length); + Arrays.sort(res); // 是对 res 排序,nums 中顺序还要保持 + int[] hash = new int[101]; // 使用哈希表,记录比当前元素小的元素个数 + for (int i = res.length - 1; i >= 0; i--) { // 注意:从后向前 + hash[res[i]] = i; // 排序后,当前下标即表示比当前元素小的元素个数 + } + // 此时 hash中保存的每一个元素数值 便是 小于这个数值的个数 + for (int i = 0; i < res.length; i++) { + res[i] = hash[nums[i]]; + } + return res; + } +} +``` + + + ## Python ```python @@ -143,4 +186,3 @@ public: * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
- From 220ceea1edd9f5e4299eb5e6814febecb9a60573 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Fri, 30 Jul 2021 15:14:16 -0400 Subject: [PATCH 18/25] =?UTF-8?q?Update=200106.=E4=BB=8E=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一版本隐藏了些细节. 代码格式不遵循PEP8 新版本代码改进格式并且加上注释. 同时每一步都是按照题解写出, 虽然比起上版本方法略显冗长, 但是更加利于理解. 方便初学者学习. --- ...序与后序遍历序列构造二叉树.md | 77 ++++++++++++------- 1 file changed, 51 insertions(+), 26 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 4c5a70a0..4bdc228d 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -654,43 +654,68 @@ class Solution { ``` Python: + 105.从前序与中序遍历序列构造二叉树 ```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -//递归法 class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: - if not preorder: return None //特殊情况 - root = TreeNode(preorder[0]) //新建父节点 - p=inorder.index(preorder[0]) //找到父节点在中序遍历的位置(因为没有重复的元素,才可以这样找) - root.left = self.buildTree(preorder[1:p+1],inorder[:p]) //注意左节点时分割中序数组和前续数组的开闭环 - root.right = self.buildTree(preorder[p+1:],inorder[p+1:]) //分割中序数组和前续数组 - return root + # 第一步: 特殊情况讨论: 树为空. 或者说是递归终止条件 + if not preorder: + return None + + # 第二步: 前序遍历的第一个就是当前的中间节点. + root_val = preorder[0] + root = TreeNode(root_val) + + # 第三步: 找切割点. + separator_idx = inorder.index(root_val) + + # 第四步: 切割inorder数组. 得到inorder数组的左,右半边. + inorder_left = inorder[:separator_idx] + inorder_right = inorder[separator_idx + 1:] + + # 第五步: 切割preorder数组. 得到preorder数组的左,右半边. + # ⭐️ 重点1: 中序数组大小一定跟前序数组大小是相同的. + preorder_left = preorder[1:1 + len(inorder_left)] + preorder_right = preorder[1 + len(inorder_left):] + + # 第六步: 递归 + root.left = self.buildTree(preorder_left, inorder_left) + root.right = self.buildTree(preorder_right, inorder_right) + + return root ``` 106.从中序与后序遍历序列构造二叉树 ```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -//递归法 class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: - if not postorder: return None //特殊情况 - root = TreeNode(postorder[-1]) //新建父节点 - p=inorder.index(postorder[-1]) //找到父节点在中序遍历的位置*因为没有重复的元素,才可以这样找 - root.left = self.buildTree(inorder[:p],postorder[:p]) //分割中序数组和后续数组 - root.right = self.buildTree(inorder[p+1:],postorder[p:-1]) //注意右节点时分割中序数组和后续数组的开闭环 - return root + # 第一步: 特殊情况讨论: 树为空. (递归终止条件) + if not postorder: + return None + + # 第二步: 后序遍历的最后一个就是当前的中间节点. + root_val = postorder[-1] + root = TreeNode(root_val) + + # 第三步: 找切割点. + separator_idx = inorder.index(root_val) + + # 第四步: 切割inorder数组. 得到inorder数组的左,右半边. + inorder_left = inorder[:separator_idx] + inorder_right = inorder[separator_idx + 1:] + + # 第五步: 切割postorder数组. 得到postorder数组的左,右半边. + # ⭐️ 重点1: 中序数组大小一定跟后序数组大小是相同的. + postorder_left = postorder[:len(inorder_left)] + postorder_right = postorder[len(inorder_left): len(postorder) - 1] + + # 第六步: 递归 + root.left = self.buildTree(inorder_left, postorder_left) + root.right = self.buildTree(inorder_right, postorder_right) + + return root ``` Go: > 106 从中序与后序遍历序列构造二叉树 From 4764d993b26a3a912646f810095c49142d497be8 Mon Sep 17 00:00:00 2001 From: posper Date: Sat, 31 Jul 2021 10:20:56 +0800 Subject: [PATCH 19/25] =?UTF-8?q?657.=E6=9C=BA=E5=99=A8=E4=BA=BA=E8=83=BD?= =?UTF-8?q?=E5=90=A6=E8=BF=94=E5=9B=9E=E5=8E=9F=E7=82=B9=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0python3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0657.机器人能否返回原点.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index b1fb6f21..ba682a33 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -91,6 +91,20 @@ class Solution { ## Python ```python +class Solution: + def judgeCircle(self, moves: str) -> bool: + x = 0 # 记录当前位置 + y = 0 + for i in range(len(moves)): + if (moves[i] == 'U'): + y += 1 + if (moves[i] == 'D'): + y -= 1 + if (moves[i] == 'L'): + x += 1 + if (moves[i] == 'R'): + x -= 1 + return x == 0 and y == 0 ``` ## Go From 0e832d518357bb239d84e294e08a3ccecec669ea Mon Sep 17 00:00:00 2001 From: posper Date: Sat, 31 Jul 2021 10:28:14 +0800 Subject: [PATCH 20/25] =?UTF-8?q?657.=E6=9C=BA=E5=99=A8=E4=BA=BA=E8=83=BD?= =?UTF-8?q?=E5=90=A6=E8=BF=94=E5=9B=9E=E5=8E=9F=E7=82=B9=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0JavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0657.机器人能否返回原点.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index ba682a33..805a81e6 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -91,6 +91,8 @@ class Solution { ## Python ```python +# 时间复杂度:O(n) +# 空间复杂度:O(1) class Solution: def judgeCircle(self, moves: str) -> bool: x = 0 # 记录当前位置 @@ -115,6 +117,19 @@ class Solution: ## JavaScript ```js +// 时间复杂度:O(n) +// 空间复杂度:O(1) +var judgeCircle = function(moves) { + var x = 0; // 记录当前位置 + var y = 0; + for (var i = 0; i < moves.length; i++) { + if (moves[i] == 'U') y++; + if (moves[i] == 'D') y--; + if (moves[i] == 'L') x++; + if (moves[i] == 'R') x--; + } + return x == 0 && y == 0; +}; ``` ----------------------- From 4851af73ab4ed58b71c1c6d1223c39d2483816ee Mon Sep 17 00:00:00 2001 From: posper Date: Sat, 31 Jul 2021 10:36:59 +0800 Subject: [PATCH 21/25] =?UTF-8?q?657.=E6=9C=BA=E5=99=A8=E4=BA=BA=E8=83=BD?= =?UTF-8?q?=E5=90=A6=E8=BF=94=E5=9B=9E=E5=8E=9F=E7=82=B9=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0657.机器人能否返回原点.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index 805a81e6..9b43ea6c 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -112,6 +112,25 @@ class Solution: ## Go ```go +func judgeCircle(moves string) bool { + x := 0 + y := 0 + for i := 0; i < len(moves); i++ { + if moves[i] == 'U' { + y++ + } + if moves[i] == 'D' { + y-- + } + if moves[i] == 'L' { + x++ + } + if moves[i] == 'R' { + x-- + } + } + return x == 0 && y == 0; +} ``` ## JavaScript From 4f5ebdabca741e124269cb5d139eaf816b5e8f4a Mon Sep 17 00:00:00 2001 From: reoooh Date: Sun, 1 Aug 2021 00:01:37 +0800 Subject: [PATCH 22/25] =?UTF-8?q?=E6=B7=BB=E5=8A=A00206=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20Ruby=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0206.翻转链表.md | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 963d7916..4efdda3b 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -275,7 +275,50 @@ var reverseList = function(head) { }; ``` +Ruby: +```ruby +# 双指针 +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +def reverse_list(head) + # return nil if head.nil? # 循环判断条件亦能起到相同作用因此不必单独判断 + cur, per = head, nil + until cur.nil? + tem = cur.next + cur.next = per + per = cur + cur = tem + end + per +end + +# 递归 +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +def reverse_list(head) + reverse(nil, head) +end + +def reverse(pre, cur) + return pre if cur.nil? + tem = cur.next + cur.next = pre + reverse(cur, tem) # 通过递归实现双指针法中的更新操作 +end +``` ----------------------- From 5d1c0883079d6e791804e086e928882a7c091831 Mon Sep 17 00:00:00 2001 From: posper Date: Sun, 1 Aug 2021 11:16:22 +0800 Subject: [PATCH 23/25] =?UTF-8?q?232.=E7=94=A8=E6=A0=88=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E9=98=9F=E5=88=97=EF=BC=8C=E4=B9=8B=E5=89=8D=E7=9A=84js?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=94=BE=E5=88=B0=E4=BA=86go=E7=9A=84?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=9D=97=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 6890fc2b..32476d6f 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -384,7 +384,7 @@ func (this *MyQueue) Peek() int { func (this *MyQueue) Empty() bool { return len(this.stack) == 0 && len(this.back) == 0 } - +``` javaScript: @@ -442,8 +442,6 @@ MyQueue.prototype.empty = function() { ``` - - ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) From 7757a60d0ebbe729443be57adccfe3716837dfc9 Mon Sep 17 00:00:00 2001 From: posper Date: Sun, 1 Aug 2021 11:20:13 +0800 Subject: [PATCH 24/25] =?UTF-8?q?34.=E5=9C=A8=E6=8E=92=E5=BA=8F=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE=E5=85=83=E7=B4=A0=E7=9A=84?= =?UTF-8?q?=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=92=8C=E6=9C=80=E5=90=8E=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E4=BD=8D=E7=BD=AE=EF=BC=8CJava=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E8=A7=A3=E6=B3=952=E6=B3=A8=E9=87=8A=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...序数组中查找元素的第一个和最后一个位置.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index 97b9a9b6..f6b01dae 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -223,7 +223,7 @@ class Solution { // 解法2 // 1、首先,在 nums 数组中二分查找 target; // 2、如果二分查找失败,则 binarySearch 返回 -1,表明 nums 中没有 target。此时,searchRange 直接返回 {-1, -1}; -// 3、如果二分查找失败,则 binarySearch 返回 nums 中 为 target 的一个下标。然后,通过左右滑动指针,来找到符合题意的区间 +// 3、如果二分查找成功,则 binarySearch 返回 nums 中值为 target 的一个下标。然后,通过左右滑动指针,来找到符合题意的区间 class Solution { public int[] searchRange(int[] nums, int target) { From 173618289d531b74e1a7e04972d88dcb790a9ac0 Mon Sep 17 00:00:00 2001 From: YellowPeaches <326826436@qq.com> Date: Sun, 1 Aug 2021 13:44:57 +0800 Subject: [PATCH 25/25] =?UTF-8?q?=E6=9B=B4=E6=96=B0143.=E9=87=8D=E6=8E=92?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20=E5=A2=9E=E5=8A=A0Java=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0143.重排链表.md | 49 ++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index c4e8d8f7..dc0095d3 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -1,4 +1,3 @@ -

@@ -63,6 +62,7 @@ public: ## 方法二 把链表放进双向队列,然后通过双向队列一前一后弹出数据,来构造新的链表。这种方法比操作数组容易一些,不用双指针模拟一前一后了 + ```C++ class Solution { public: @@ -176,6 +176,51 @@ public: Java: +```java +public class ReorderList { + public void reorderList(ListNode head) { + ListNode fast = head, slow = head; + //求出中点 + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + //right就是右半部分 12345 就是45 1234 就是34 + ListNode right = slow.next; + //断开左部分和右部分 + slow.next = null; + //反转右部分 right就是反转后右部分的起点 + right = reverseList(right); + //左部分的起点 + ListNode left = head; + //进行左右部分来回连接 + //这里左部分的节点个数一定大于等于右部分的节点个数 因此只判断right即可 + while (right != null) { + ListNode curLeft = left.next; + left.next = right; + left = curLeft; + + ListNode curRight = right.next; + right.next = left; + right = curRight; + } + } + + public ListNode reverseList(ListNode head) { + ListNode headNode = new ListNode(0); + ListNode cur = head; + ListNode next = null; + while (cur != null) { + next = cur.next; + cur.next = headNode.next; + headNode.next = cur; + cur = next; + } + return headNode.next; + } +} +``` + Python: Go: @@ -183,8 +228,10 @@ Go: JavaScript: ----------------------- + * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +