From f39d5a110c19963037374a3f1ea253b30f08becb Mon Sep 17 00:00:00 2001 From: erdengk <15596570256@163.com> Date: Wed, 16 Feb 2022 16:23:39 +0800 Subject: [PATCH 01/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E9=94=99=E5=AD=97=20&=20=E4=BC=98=E5=8C=96=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=90=8D=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...序与后序遍历序列构造二叉树.md | 4 ++-- problems/0860.柠檬水找零.md | 20 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 30ec684d..cb1d75d9 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -89,9 +89,9 @@ TreeNode* traversal (vector& inorder, vector& postorder) { **难点大家应该发现了,就是如何切割,以及边界值找不好很容易乱套。** -此时应该注意确定切割的标准,是左闭右开,还有左开又闭,还是左闭又闭,这个就是不变量,要在递归中保持这个不变量。 +此时应该注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量。 -**在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭又闭,必然乱套!** +**在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭右闭,必然乱套!** 我在[数组:每次遇到二分法,都是一看就会,一写就废](https://programmercarl.com/0035.搜索插入位置.html)和[数组:这个循环可以转懵很多人!](https://programmercarl.com/0059.螺旋矩阵II.html)中都强调过循环不变量的重要性,在二分查找以及螺旋矩阵的求解中,坚持循环不变量非常重要,本题也是。 diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index 01bd1a3b..f48ecf4d 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -128,24 +128,24 @@ public: ```java class Solution { public boolean lemonadeChange(int[] bills) { - int cash_5 = 0; - int cash_10 = 0; + int five = 0; + int ten = 0; for (int i = 0; i < bills.length; i++) { if (bills[i] == 5) { - cash_5++; + five++; } else if (bills[i] == 10) { - cash_5--; - cash_10++; + five--; + ten++; } else if (bills[i] == 20) { - if (cash_10 > 0) { - cash_10--; - cash_5--; + if (ten > 0) { + ten--; + five--; } else { - cash_5 -= 3; + five -= 3; } } - if (cash_5 < 0 || cash_10 < 0) return false; + if (five < 0 || ten < 0) return false; } return true; From 1a553b01d691478c049fd39e59548f3a71c9f456 Mon Sep 17 00:00:00 2001 From: erdengk <15596570256@163.com> Date: Wed, 16 Feb 2022 17:43:36 +0800 Subject: [PATCH 02/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92?= =?UTF-8?q?=E5=A2=9E=E5=AD=90=E5=BA=8F=E5=88=97.md=20Java=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 34 +++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 6d88119e..298586c7 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -227,7 +227,39 @@ class Solution { } } ``` - +```java +//法二:使用map +class Solution { + //结果集合 + List> res = new ArrayList<>(); + //路径集合 + LinkedList path = new LinkedList<>(); + public List> findSubsequences(int[] nums) { + getSubsequences(nums,0); + return res; + } + private void getSubsequences( int[] nums, int start ) { + if(path.size()>1 ){ + res.add( new ArrayList<>(path) ); + // 注意这里不要加return,要取树上的节点 + } + HashMap map = new HashMap<>(); + for(int i=start ;i < nums.length ;i++){ + if(!path.isEmpty() && nums[i]< path.getLast()){ + continue; + } + // 使用过了当前数字 + if ( map.getOrDefault( nums[i],0 ) >=1 ){ + continue; + } + map.put(nums[i],map.getOrDefault( nums[i],0 )+1); + path.add( nums[i] ); + getSubsequences( nums,i+1 ); + path.removeLast(); + } + } +} +``` ### Python From fac4fc5193caac05a5418338f281e25c02a2739b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 16 Feb 2022 23:22:26 +0800 Subject: [PATCH 03/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880617.=E5=90=88?= =?UTF-8?q?=E5=B9=B6=E4=BA=8C=E5=8F=89=E6=A0=91.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0617.合并二叉树.md | 50 ++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index f815d741..55786ea9 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -583,6 +583,56 @@ var mergeTrees = function(root1, root2) { ``` +## TypeScript + +> 递归法: + +```type +function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 === null) return root2; + if (root2 === null) return root1; + const resNode: TreeNode = new TreeNode(root1.val + root2.val); + resNode.left = mergeTrees(root1.left, root2.left); + resNode.right = mergeTrees(root1.right, root2.right); + return resNode; +}; +``` + +> 迭代法: + +```typescript +function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 === null) return root2; + if (root2 === null) return root1; + const helperQueue1: TreeNode[] = [], + helperQueue2: TreeNode[] = []; + helperQueue1.push(root1); + helperQueue2.push(root2); + let tempNode1: TreeNode, + tempNode2: TreeNode; + while (helperQueue1.length > 0) { + tempNode1 = helperQueue1.shift()!; + tempNode2 = helperQueue2.shift()!; + tempNode1.val += tempNode2.val; + if (tempNode1.left !== null && tempNode2.left !== null) { + helperQueue1.push(tempNode1.left); + helperQueue2.push(tempNode2.left); + } else if (tempNode1.left === null) { + tempNode1.left = tempNode2.left; + } + if (tempNode1.right !== null && tempNode2.right !== null) { + helperQueue1.push(tempNode1.right); + helperQueue2.push(tempNode2.right); + } else if (tempNode1.right === null) { + tempNode1.right = tempNode2.right; + } + } + return root1; +}; +``` + + + -----------------------
From bd2310622b8a4d726288759820a60b5a62fce590 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 17 Feb 2022 10:25:56 +0800 Subject: [PATCH 04/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880700.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C?= =?UTF-8?q?=E7=B4=A2.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?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/0700.二叉搜索树中的搜索.md | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 1521514a..00ba8753 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -334,6 +334,36 @@ var searchBST = function (root, val) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function searchBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null || root.val === val) return root; + if (root.val < val) return searchBST(root.right, val); + if (root.val > val) return searchBST(root.left, val); + return null; +}; +``` + +> 迭代法 + +```typescript +function searchBST(root: TreeNode | null, val: number): TreeNode | null { + let resNode: TreeNode | null = root; + while (resNode !== null) { + if (resNode.val === val) return resNode; + if (resNode.val < val) { + resNode = resNode.right; + } else { + resNode = resNode.left; + } + } + return null; +}; +``` + ----------------------- From 7af58b92b86e045998ce3f7ceca186d73809cbdd Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 17 Feb 2022 15:07:13 +0800 Subject: [PATCH 05/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880098.=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 4ed29619..c0f3e039 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -526,6 +526,48 @@ var isValidBST = function (root) { }; ``` +## TypeScript + +> 辅助数组解决: + +```typescript +function isValidBST(root: TreeNode | null): boolean { + const traversalArr: number[] = []; + function inorderTraverse(root: TreeNode | null): void { + if (root === null) return; + inorderTraverse(root.left); + traversalArr.push(root.val); + inorderTraverse(root.right); + } + inorderTraverse(root); + for (let i = 0, length = traversalArr.length; i < length - 1; i++) { + if (traversalArr[i] >= traversalArr[i + 1]) return false; + } + return true; +}; +``` + +> 递归中解决: + +```typescript +function isValidBST(root: TreeNode | null): boolean { + let maxVal = -Infinity; + function inorderTraverse(root: TreeNode | null): boolean { + if (root === null) return true; + let leftValid: boolean = inorderTraverse(root.left); + if (!leftValid) return false; + if (maxVal < root.val) { + maxVal = root.val + } else { + return false; + } + let rightValid: boolean = inorderTraverse(root.right); + return leftValid && rightValid; + } + return inorderTraverse(root); +}; +``` + ----------------------- From 6cb2076827726fc5be341e226585882424e523e7 Mon Sep 17 00:00:00 2001 From: hs-zhangsan <1513157458@qq.com> Date: Fri, 18 Feb 2022 17:03:41 +0800 Subject: [PATCH 06/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20541.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 14b8601a..bf59f52d 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -98,8 +98,31 @@ public: ## 其他语言版本 +C: + +```c +char * reverseStr(char * s, int k){ + int len = strlen(s); + + for (int i = 0; i < len; i += (2 * k)) { + //判断剩余字符是否少于 k + k = i + k > len ? len - i : k; + + int left = i; + int right = i + k - 1; + while (left < right) { + char temp = s[left]; + s[left++] = s[right]; + s[right--] = temp; + } + } + + return s; +} +``` Java: + ```Java //解法一 class Solution { From f5fe6bd73c936faedc52b93de3cd56ec39c0ec84 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 18 Feb 2022 23:33:57 +0800 Subject: [PATCH 07/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88530.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F?= =?UTF-8?q?=E7=BB=9D=E5=AF=B9=E5=B7=AE=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0530.二叉搜索树的最小绝对差.md | 71 ++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 3ebb4c8c..77699c9f 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -238,7 +238,7 @@ class Solution: cur = cur.right return result -``` +``` ## Go: @@ -364,5 +364,74 @@ var getMinimumDifference = function(root) { } ``` +## TypeScript + +> 辅助数组解决 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + let helperArr: number[] = []; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.left); + helperArr.push(root.val); + recur(root.right); + } + recur(root); + let resMin: number = Infinity; + for (let i = 0, length = helperArr.length; i < length - 1; i++) { + resMin = Math.min(resMin, helperArr[i + 1] - helperArr[i]); + } + return resMin; +}; +``` + +> 递归中解决 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + let preNode: TreeNode | null= null; + let resMin: number = Infinity; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.left); + if (preNode !== null) { + resMin = Math.min(resMin, root.val - preNode.val); + } + preNode = root; + recur(root.right); + } + recur(root); + return resMin; +}; +``` + +> 迭代法-中序遍历 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + const helperStack: TreeNode[] = []; + let curNode: TreeNode | null = root; + let resMin: number = Infinity; + let preNode: TreeNode | null = null; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + if (preNode !== null) { + resMin = Math.min(resMin, curNode.val - preNode.val); + } + preNode = curNode; + curNode = curNode.right; + } + } + return resMin; +}; +``` + + + -----------------------
From 28cff716ac11f9f5970593fb42a38b399eae9490 Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 11:52:30 +0800 Subject: [PATCH 08/38] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index c481fd11..9e131c6d 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -34,19 +34,19 @@ 1. **确定递归函数的参数和返回值**:因为要打印出前序遍历节点的数值,所以参数里需要传入vector在放节点的数值,除了这一点就不需要在处理什么数据了也不需要有返回值,所以递归函数返回类型就是void,代码如下: -``` +```cpp void traversal(TreeNode* cur, vector& vec) ``` 2. **确定终止条件**:在递归的过程中,如何算是递归结束了呢,当然是当前遍历的节点是空了,那么本层递归就要要结束了,所以如果当前遍历的这个节点是空,就直接return,代码如下: -``` +```cpp if (cur == NULL) return; ``` 3. **确定单层递归的逻辑**:前序遍历是中左右的循序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下: -``` +```cpp vec.push_back(cur->val); // 中 traversal(cur->left, vec); // 左 traversal(cur->right, vec); // 右 From a9ae0f5d03b4e6f819c3c3d518f2984cf54d8810 Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 11:55:45 +0800 Subject: [PATCH 09/38] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86=EF=BC=9A=E8=A1=A5=E5=85=85?= =?UTF-8?q?Swift=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/二叉树的迭代遍历.md --- problems/二叉树的迭代遍历.md | 104 ++++++++++++--------------- 1 file changed, 45 insertions(+), 59 deletions(-) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index ba38726b..8164724b 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -390,7 +390,7 @@ func inorderTraversal(root *TreeNode) []int { } ``` -javaScript +javaScript: ```js @@ -454,7 +454,7 @@ var postorderTraversal = function(root, res = []) { }; ``` -TypeScript: +TypeScript: ```typescript // 前序遍历(迭代法) @@ -509,77 +509,63 @@ function postorderTraversal(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: -> 迭代法前序遍历 ```swift +// 前序遍历迭代法 func preorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - stack.append(root!) + var result = [Int]() + guard let root = root else { return result } + var stack = [root] while !stack.isEmpty { - let node = stack.popLast()! - res.append(node.val) - if node.right != nil { - stack.append(node.right!) + let current = stack.removeLast() + // 先右后左,这样出栈的时候才是左右顺序 + if let node = current.right { // 右 + stack.append(node) } - if node.left != nil { - stack.append(node.left!) + if let node = current.left { // 左 + stack.append(node) } + result.append(current.val) // 中 } - return res + return result } -``` -> 迭代法中序遍历 -```swift -func inorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - var cur: TreeNode? = root - while cur != nil || !stack.isEmpty { - if cur != nil { - stack.append(cur!) - cur = cur!.left - } else { - cur = stack.popLast() - res.append(cur!.val) - cur = cur!.right - } - } - return res -} -``` - -> 迭代法后序遍历 -```swift +// 后序遍历迭代法 func postorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - stack.append(root!) - // res 存储 中 -> 右 -> 左 + var result = [Int]() + guard let root = root else { return result } + var stack = [root] while !stack.isEmpty { - let node = stack.popLast()! - res.append(node.val) - if node.left != nil { - stack.append(node.left!) + let current = stack.removeLast() + // 与前序相反,即中右左,最后结果还需反转才是后序 + if let node = current.left { // 左 + stack.append(node) } - if node.right != nil { - stack.append(node.right!) + if let node = current.right { // 右 + stack.append(node) + } + result.append(current.val) // 中 + } + return result.reversed() +} + +// 中序遍历迭代法 +func inorderTraversal(_ root: TreeNode?) -> [Int] { + var result = [Int]() + var stack = [TreeNode]() + var current: TreeNode! = root + while current != nil || !stack.isEmpty { + if current != nil { // 先访问到最左叶子 + stack.append(current) + current = current.left // 左 + } else { + current = stack.removeLast() + result.append(current.val) // 中 + current = current.right // 右 } } - // res 翻转 - res.reverse() - return res + return result } ``` From af547486756b7213d17c10dd76c1a6e518a9b1fa Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 14:57:57 +0800 Subject: [PATCH 10/38] =?UTF-8?q?0102.=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85Swift=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/0102.二叉树的层序遍历.md --- problems/0102.二叉树的层序遍历.md | 332 ++++++++++------------ 1 file changed, 156 insertions(+), 176 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1a92d42f..8d6d2502 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -273,32 +273,29 @@ function levelOrder(root: TreeNode | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrder(_ root: TreeNode?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } - var queue = [TreeNode]() - queue.append(root) + var result = [[Int]]() + guard let root = root else { return result } + // 表示一层 + var queue = [root] while !queue.isEmpty { - let size = queue.count - var sub = [Int]() - for _ in 0 ..< size { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + subarray.append(node.val) + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(sub) + result.append(subarray) } - return res + + return result } ``` @@ -505,30 +502,29 @@ function levelOrderBottom(root: TreeNode | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } - var queue: [TreeNode] = [root] + // 表示一层 + var queue = [TreeNode]() + if let node = root { queue.append(node) } + var result = [[Int]]() while !queue.isEmpty { - var sub = [Int]() - for _ in 0 ..< queue.count { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + subarray.append(node.val) + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node)} } - res.insert(sub, at: 0) + result.append(subarray) } - return res + + return result.reversed() } ``` @@ -729,37 +725,31 @@ function rightSideView(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func rightSideView(_ root: TreeNode?) -> [Int] { - var res = [Int]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Int]() while !queue.isEmpty { - let size = queue.count - for i in 0 ..< size { + let count = queue.count + for i in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if i == size - 1 { - // 保存 每层最后一个元素 - res.append(node.val) - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + if i == count - 1 { result.append(node.val) } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } } - return res + + return result } ``` - # 637.二叉树的层平均值 [力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/) @@ -965,32 +955,30 @@ function averageOfLevels(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func averageOfLevels(_ root: TreeNode?) -> [Double] { - var res = [Double]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Double]() while !queue.isEmpty { - let size = queue.count + let count = queue.count var sum = 0 - for _ in 0 ..< size { + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() sum += node.val - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(Double(sum) / Double(size)) + result.append(Double(sum) / Double(count)) } - return res + + return result } ``` @@ -1212,29 +1200,28 @@ function levelOrder(root: Node | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrder(_ root: Node?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [[Int]]() while !queue.isEmpty { - let size = queue.count - var sub = [Int]() - for _ in 0 ..< size { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - for childNode in node.children { - queue.append(childNode) - } + subarray.append(node.val) + // 下一层 + for node in node.children { queue.append(node) } } - res.append(sub) + result.append(subarray) } - return res + + return result } ``` @@ -1419,34 +1406,30 @@ function largestValues(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func largestValues(_ root: TreeNode?) -> [Int] { - var res = [Int]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Int]() while !queue.isEmpty { - let size = queue.count - var max: Int = Int.min - for _ in 0 ..< size { + let count = queue.count + var max = queue[0].val + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if node.val > max { - max = node.val - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + if node.val > max { max = node.val } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(max) + result.append(max) } - return res + + return result } ``` @@ -1456,7 +1439,7 @@ func largestValues(_ root: TreeNode?) -> [Int] { 给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: -``` +```cpp struct Node { int val; Node *left; @@ -1677,33 +1660,34 @@ func connect(root *Node) *Node { } ``` -Swift: +Swift: + ```swift func connect(_ root: Node?) -> Node? { - guard let root = root else { - return nil - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } while !queue.isEmpty { - let size = queue.count - var preNode: Node? - for i in 0 ..< size { - let node = queue.removeFirst() + let count = queue.count + var current, previous: Node! + for i in 0 ..< count { + // 当前层 if i == 0 { - preNode = node + previous = queue.removeFirst() + current = previous } else { - preNode?.next = node - preNode = node - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + current = queue.removeFirst() + previous.next = current + previous = current } + + // 下一层 + if let node = current.left { queue.append(node) } + if let node = current.right { queue.append(node) } } + previous.next = nil } + return root } ``` @@ -1927,34 +1911,34 @@ func connect(root *Node) *Node { return root } ``` - Swift: + ```swift func connect(_ root: Node?) -> Node? { - guard let root = root else { - return nil - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } while !queue.isEmpty { - let size = queue.count - var preNode: Node? - for i in 0 ..< size { - let node = queue.removeFirst() + let count = queue.count + var current, previous: Node! + for i in 0 ..< count { + // 当前层 if i == 0 { - preNode = node + previous = queue.removeFirst() + current = previous } else { - preNode?.next = node - preNode = node - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + current = queue.removeFirst() + previous.next = current + previous = current } + + // 下一层 + if let node = current.left { queue.append(node) } + if let node = current.right { queue.append(node) } } + previous.next = nil } + return root } ``` @@ -2151,29 +2135,28 @@ function maxDepth(root: TreeNode | null): number { }; ``` -Swift: +Swift: ```swift func maxDepth(_ root: TreeNode?) -> Int { - guard let root = root else { - return 0 - } + guard root != nil else { return 0 } + var depth = 0 var queue = [TreeNode]() - queue.append(root) - var res: Int = 0 + queue.append(root!) while !queue.isEmpty { - for _ in 0 ..< queue.count { + let count = queue.count + depth += 1 + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res += 1 } - return res + + return depth } ``` @@ -2374,28 +2357,25 @@ Swift: ```swift func minDepth(_ root: TreeNode?) -> Int { - guard let root = root else { - return 0 - } - var res = 0 - var queue = [TreeNode]() - queue.append(root) + guard root != nil else { return 0 } + var depth = 0 + var queue = [root!] while !queue.isEmpty { - res += 1 - for _ in 0 ..< queue.count { + let count = queue.count + depth += 1 + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if node.left == nil && node.right == nil { - return res - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + if node.left == nil, node.right == nil { // 遇到叶子结点则返回 + return depth } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } } - return res + return depth } ``` From 53d4999ad8e7b16a790a8cfcdb6a0f030ec96dfd Mon Sep 17 00:00:00 2001 From: bqlin Date: Sat, 25 Dec 2021 17:14:15 +0800 Subject: [PATCH 11/38] =?UTF-8?q?0226.=E7=BF=BB=E8=BD=AC=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C?= =?UTF-8?q?=E8=A1=A5=E5=85=85Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/0226.翻转二叉树.md --- problems/0226.翻转二叉树.md | 63 +++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 8108e7ad..a3ebe24d 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -47,8 +47,6 @@ ## 递归法 - - 对于二叉树的递归法的前中后序遍历,已经在[二叉树:前中后序递归遍历](https://programmercarl.com/二叉树的递归遍历.html)详细讲解了。 我们下文以前序遍历为例,通过动画来看一下翻转的过程: @@ -63,7 +61,7 @@ 返回值的话其实也不需要,但是题目中给出的要返回root节点的指针,可以直接使用题目定义好的函数,所以就函数的返回类型为`TreeNode*`。 -``` +```cpp TreeNode* invertTree(TreeNode* root) ``` @@ -71,7 +69,7 @@ TreeNode* invertTree(TreeNode* root) 当前节点为空的时候,就返回 -``` +```cpp if (root == NULL) return root; ``` @@ -79,7 +77,7 @@ if (root == NULL) return root; 因为是先前序遍历,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。 -``` +```cpp swap(root->left, root->right); invertTree(root->left); invertTree(root->right); @@ -257,7 +255,7 @@ public: ## 其他语言版本 -### Java: +### Java ```Java //DFS递归 @@ -469,8 +467,6 @@ func invertTree(root *TreeNode) *TreeNode { } ``` - - ### JavaScript 使用递归版本的前序遍历 @@ -690,7 +686,7 @@ function invertTree(root: TreeNode | null): TreeNode | null { }; ``` -### C: +### C 递归法 ```c @@ -775,5 +771,54 @@ func invertTree1(_ root: TreeNode?) -> TreeNode? { } ``` +### Swift + +深度优先递归。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + swap(&node.left, &node.right) + _ = invertTree(node.left) + _ = invertTree(node.right) + return root +} +``` + +深度优先迭代,子结点顺序不重要,从根结点出发深度遍历即可。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + var stack = [node] + while !stack.isEmpty { + guard let node = stack.popLast() else { break } + swap(&node.left, &node.right) + if let node = node.left { stack.append(node) } + if let node = node.right { stack.append(node) } + } + return root +} +``` + +广度优先迭代。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + var queue = [node] + while !queue.isEmpty { + let count = queue.count + for _ in 0 ..< count { + let node = queue.removeFirst() + swap(&node.left, &node.right) + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } + } + } + return root +} +``` + -----------------------
From 9b991d89948d5793f1f93cedb7d0c2093586506e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 19 Feb 2022 15:05:26 +0800 Subject: [PATCH 12/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880501.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97?= =?UTF-8?q?=E6=95=B0.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?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/0501.二叉搜索树中的众数.md | 105 ++++++++++++++++++- 1 file changed, 103 insertions(+), 2 deletions(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 277f46f5..1be9ee6a 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -512,7 +512,7 @@ class Solution: self.search_BST(cur.right) ``` - + > 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性 ```python3 @@ -661,7 +661,7 @@ var findMode = function(root) { } return res; }; -``` +``` 不使用额外空间,利用二叉树性质,中序遍历(有序): @@ -699,6 +699,107 @@ var findMode = function(root) { }; ``` +## TypeScript + +> 辅助Map法 + +```typescript +function findMode(root: TreeNode | null): number[] { + if (root === null) return []; + const countMap: Map = new Map(); + function traverse(root: TreeNode | null): void { + if (root === null) return; + countMap.set(root.val, (countMap.get(root.val) || 0) + 1); + traverse(root.left); + traverse(root.right); + } + traverse(root); + const countArr: number[][] = Array.from(countMap); + countArr.sort((a, b) => { + return b[1] - a[1]; + }) + const resArr: number[] = []; + const maxCount: number = countArr[0][1]; + for (let i of countArr) { + if (i[1] === maxCount) resArr.push(i[0]); + } + return resArr; +}; +``` + +> 递归中直接解决 + +```typescript +function findMode(root: TreeNode | null): number[] { + let preNode: TreeNode | null = null; + let maxCount: number = 0; + let count: number = 0; + let resArr: number[] = []; + function traverse(root: TreeNode | null): void { + if (root === null) return; + traverse(root.left); + if (preNode === null) { // 第一个节点 + count = 1; + } else if (preNode.val === root.val) { + count++; + } else { + count = 1; + } + if (count === maxCount) { + resArr.push(root.val); + } else if (count > maxCount) { + maxCount = count; + resArr.length = 0; + resArr.push(root.val); + } + preNode = root; + traverse(root.right); + } + traverse(root); + return resArr; +}; +``` + +> 迭代法 + +```typescript +function findMode(root: TreeNode | null): number[] { + const helperStack: TreeNode[] = []; + const resArr: number[] = []; + let maxCount: number = 0; + let count: number = 0; + let preNode: TreeNode | null = null; + let curNode: TreeNode | null = root; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + if (preNode === null) { // 第一个节点 + count = 1; + } else if (preNode.val === curNode.val) { + count++; + } else { + count = 1; + } + if (count === maxCount) { + resArr.push(curNode.val); + } else if (count > maxCount) { + maxCount = count; + resArr.length = 0; + resArr.push(curNode.val); + } + preNode = curNode; + curNode = curNode.right; + } + } + return resArr; +}; +``` + + + -----------------------
From 292fe1eb380622ce4fc19f2d05ef26bb472e855d Mon Sep 17 00:00:00 2001 From: hs-zhangsan <1513157458@qq.com> Date: Sat, 19 Feb 2022 15:55:31 +0800 Subject: [PATCH 13/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=91=E6=8C=87Of?= =?UTF-8?q?fer=2005.=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 530545fb..9e743887 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -121,6 +121,37 @@ for (int i = 0; i < a.size(); i++) { ## 其他语言版本 +C: +```C +char* replaceSpace(char* s){ + //统计空格数量 + int count = 0; + int len = strlen(s); + for (int i = 0; i < len; i++) { + if (s[i] == ' ') { + count++; + } + } + + //为新数组分配空间 + int newLen = len + count * 2; + char* result = malloc(sizeof(char) * newLen + 1); + //填充新数组并替换空格 + for (int i = len - 1, j = newLen - 1; i >= 0; i--, j--) { + if (s[i] != ' ') { + result[j] = s[i]; + } else { + result[j--] = '0'; + result[j--] = '2'; + result[j] = '%'; + } + } + result[newLen] = '\0'; + + return result; +} +``` + Java: ```Java From bb277e08e19b797a1b5da5bfe0c60ef84b5c9c8e Mon Sep 17 00:00:00 2001 From: K-945 <393763635@qq.com> Date: Sun, 20 Feb 2022 17:56:21 +0800 Subject: [PATCH 14/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A00059.=E8=9E=BA=E6=97=8B?= =?UTF-8?q?=E7=9F=A9=E9=98=B5II.md=20=E5=92=8C=E8=A7=A3=E6=9E=90=E7=9B=B8?= =?UTF-8?q?=E5=90=8C=E7=9A=84python=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 60 ++++++++++++--------------------- 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 3f7a59ca..a98e72ad 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -192,47 +192,31 @@ python: ```python3 class Solution: - def generateMatrix(self, n: int) -> List[List[int]]: - # 初始化要填充的正方形 - matrix = [[0] * n for _ in range(n)] + nums = [[0] * n for _ in range(n)] + startx, starty = 0, 0 # 起始点 + loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点 + count = 1 # 计数 - left, right, up, down = 0, n - 1, 0, n - 1 - number = 1 # 要填充的数字 + for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从1开始 + for i in range(starty, n - offset) : # 从左至右,左闭右开 + nums[startx][i] = count + count += 1 + for i in range(startx, n - offset) : # 从上至下 + nums[i][n - offset] = count + count += 1 + for i in range(n - offset, starty, -1) : # 从右至左 + nums[n - offset][i] = count + count += 1 + for i in range(n - offset, startx, -1) : # 从下至上 + nums[i][starty] = count + count += 1 + startx += 1 # 更新起始点 + starty += 1 - while left < right and up < down: - - # 从左到右填充上边 - for x in range(left, right): - matrix[up][x] = number - number += 1 - - # 从上到下填充右边 - for y in range(up, down): - matrix[y][right] = number - number += 1 - - # 从右到左填充下边 - for x in range(right, left, -1): - matrix[down][x] = number - number += 1 - - # 从下到上填充左边 - for y in range(down, up, -1): - matrix[y][left] = number - number += 1 - - # 缩小要填充的范围 - left += 1 - right -= 1 - up += 1 - down -= 1 - - # 如果阶数为奇数,额外填充一次中心 - if n % 2: - matrix[n // 2][n // 2] = number - - return matrix + if n % 2 != 0 : # n为奇数时,填充中心点 + nums[mid][mid] = count + return nums ``` javaScript From e54ba10fa12016132f40a2d27b128270104147db Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Thu, 24 Feb 2022 00:36:23 +0800 Subject: [PATCH 15/38] Added in one more python solution. Using defaultdict. --- problems/0454.四数相加II.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index a7c903eb..a6cd413b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -141,7 +141,24 @@ class Solution(object): ``` +```python +class Solution: + def fourSumCount(self, nums1: list, nums2: list, nums3: list, nums4: list) -> int: + from collections import defaultdict # You may use normal dict instead. + rec, cnt = defaultdict(lambda : 0), 0 + # To store the summary of all the possible combinations of nums1 & nums2, together with their frequencies. + for i in nums1: + for j in nums2: + rec[i+j] += 1 + # To add up the frequencies if the corresponding value occurs in the dictionary + for i in nums3: + for j in nums4: + cnt += rec.get(-(i+j), 0) # No matched key, return 0. + return cnt +``` + Go: + ```go func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int { m := make(map[int]int) From 5b78393ac4e70db5cf9518090f4cb563c68e11d6 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Fri, 25 Feb 2022 00:57:43 +0800 Subject: [PATCH 16/38] modified 15. Add a new version with the same idea. --- problems/0015.三数之和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index e191eabc..1d811b76 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -243,7 +243,34 @@ class Solution: right -= 1 return ans ``` +Python (v2): + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if len(nums) < 3: return [] + nums, res = sorted(nums), [] + for i in range(len(nums) - 2): + cur, l, r = nums[i], i + 1, len(nums) - 1 + if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time. + + while l < r: + if cur + nums[l] + nums[r] == 0: + res.append([cur, nums[l], nums[r]]) + # Drop duplicates for the second time in interation of l & r. Only used when target situation occurs, because that is the reason for dropping duplicates. + while l < r - 1 and nums[l] == nums[l + 1]: + l += 1 + while r > l + 1 and nums[r] == nums[r - 1]: + r -= 1 + if cur + nums[l] + nums[r] > 0: + r -= 1 + else: + l += 1 + return res +``` + Go: + ```Go func threeSum(nums []int)[][]int{ sort.Ints(nums) From 984a3ae5bc7d08bb70b05601d96d57b1b0c9c791 Mon Sep 17 00:00:00 2001 From: cylin2000 Date: Fri, 25 Feb 2022 10:56:23 +0000 Subject: [PATCH 17/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=20C#=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 | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 379cb5fc..635868a9 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -561,5 +561,51 @@ class Solution { } ``` +**C#** +```csharp +//左闭右闭 +public class Solution { + public int Search(int[] nums, int target) { + int left = 0; + int right = nums.Length - 1; + while(left <= right){ + int mid = (right - left ) / 2 + left; + if(nums[mid] == target){ + return mid; + } + else if(nums[mid] < target){ + left = mid+1; + } + else if(nums[mid] > target){ + right = mid-1; + } + } + return -1; + } +} + +//左闭右开 +public class Solution{ + public int Search(int[] nums, int target){ + int left = 0; + int right = nums.Length; + while(left < right){ + int mid = (right - left) / 2 + left; + if(nums[mid] == target){ + return mid; + } + else if(nums[mid] < target){ + left = mid + 1; + } + else if(nums[mid] > target){ + right = mid; + } + } + return -1; + } +} +``` + + -----------------------
From 3f189d4687818313a90bc240524a3dc049f39ec4 Mon Sep 17 00:00:00 2001 From: cylin2000 Date: Fri, 25 Feb 2022 10:57:05 +0000 Subject: [PATCH 18/38] Add : --- problems/0704.二分查找.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 635868a9..15e096a0 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -561,7 +561,7 @@ class Solution { } ``` -**C#** +**C#:** ```csharp //左闭右闭 public class Solution { From 4980496c05aad48ea28cc0ed471cc08ffe36b9d6 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Fri, 25 Feb 2022 18:59:56 +0800 Subject: [PATCH 19/38] 0001. Add python v2. Making use of the dictionary property. --- problems/0001.两数之和.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 22b2e7eb..9571a773 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -118,6 +118,18 @@ class Solution: 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 +``` Go: From 0738423c9ed3979fa649ba7a147c4c60ecdec616 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 00:24:13 +0800 Subject: [PATCH 20/38] modified 541. Can be more pythonic. --- problems/0541.反转字符串II.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 14b8601a..cd9bb0cc 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -204,8 +204,23 @@ class Solution: return ''.join(res) ``` +Python3 (v2): + +```python +class Solution: + def reverseStr(self, s: str, k: int) -> str: + # Two pointers. Another is inside the loop. + p = 0 + while p < len(s): + p2 = p + k + # Written in this could be more pythonic. + s = s[:p] + s[p: p2][::-1] + s[p2:] + p = p + 2 * k + return s +``` Go: + ```go func reverseStr(s string, k int) string { ss := []byte(s) From f862ebf0c70c37c62f83b5ad50b441c830f5850f Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 00:41:18 +0800 Subject: [PATCH 21/38] modified offer05. Add two python versions. --- problems/剑指Offer05.替换空格.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 530545fb..59f74a18 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -260,8 +260,24 @@ class Solution: ``` +```python +class Solution: + def replaceSpace(self, s: str) -> str: + # method 1 - Very rude + return "%20".join(s.split(" ")) + + # method 2 - Reverse the s when counting in for loop, then update from the end. + n = len(s) + for e, i in enumerate(s[::-1]): + print(i, e) + if i == " ": + s = s[: n - (e + 1)] + "%20" + s[n - e:] + print("") + return s +``` javaScript: + ```js /** * @param {string} s From 0fbacd5d9b4c72db15f5f1ddae2c73b320a8c554 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 01:19:55 +0800 Subject: [PATCH 22/38] modified 151. Add 2 python versions. No need to implement Carlo's idea in such a complecated way by inviting extra space. --- problems/0151.翻转字符串里的单词.md | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index ead5fa12..7588cbd6 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -438,6 +438,38 @@ class Solution: ``` +```python +class Solution: + def reverseWords(self, s: str) -> str: + # method 1 - Rude but work & efficient method. + s_list = [i for i in s.split(" ") if len(i) > 0] + return " ".join(s_list[::-1]) + + # method 2 - Carlo's idea + def trim_head_tail_space(ss: str): + p = 0 + while p < len(ss) and ss[p] == " ": + p += 1 + return ss[p:] + + # Trim the head and tail space + s = trim_head_tail_space(s) + s = trim_head_tail_space(s[::-1])[::-1] + + pf, ps, s = 0, 0, s[::-1] # Reverse the string. + while pf < len(s): + if s[pf] == " ": + # Will not excede. Because we have clean the tail space. + if s[pf] == s[pf + 1]: + s = s[:pf] + s[pf + 1:] + continue + else: + s = s[:ps] + s[ps: pf][::-1] + s[pf:] + ps, pf = pf + 1, pf + 2 + else: + pf += 1 + return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions, +``` Go: From 9712e3f75cbd0525eb40e0d12c264d1aa1952ea6 Mon Sep 17 00:00:00 2001 From: jinyuhang-007 <53509988+jinyuhang-007@users.noreply.github.com> Date: Sun, 27 Feb 2022 17:35:50 -0800 Subject: [PATCH 23/38] =?UTF-8?q?=E6=9B=B4=E6=96=B00005.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 37 ++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 99458825..8b3af3bb 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -260,7 +260,26 @@ public: # 其他语言版本 -## Java +Java: + +```java +public int[] twoSum(int[] nums, int target) { + int[] res = new int[2]; + if(nums == null || nums.length == 0){ + return res; + } + Map map = new HashMap<>(); + for(int i = 0; i < nums.length; i++){ + int temp = target - nums[i]; + if(map.containsKey(temp)){ + res[1] = i; + res[0] = map.get(temp); + } + map.put(nums[i], i); + } + return res; +} +``` ```java // 双指针 中心扩散法 @@ -291,7 +310,7 @@ class Solution { } ``` -## Python +Python: ```python class Solution: @@ -312,7 +331,8 @@ class Solution: return s[left:right + 1] ``` -> 双指针法: +双指针: + ```python class Solution: def longestPalindrome(self, s: str) -> str: @@ -340,13 +360,13 @@ class Solution: return s[start:end] ``` -## Go +Go: ```go ``` -## JavaScript +JavaScript: ```js //动态规划解法 @@ -462,8 +482,9 @@ var longestPalindrome = function(s) { }; ``` -## C -动态规划: +C: + +动态规划: ```c //初始化dp数组,全部初始为false bool **initDP(int strLen) { @@ -513,7 +534,7 @@ char * longestPalindrome(char * s){ } ``` -双指针: +双指针: ```c int left, maxLength; void extend(char *str, int i, int j, int size) { From ee0e80dae79071d1b48dfcc022e33f827de9c532 Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Mon, 28 Feb 2022 14:18:29 +0800 Subject: [PATCH 24/38] =?UTF-8?q?0700=20=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=20=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= =?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/0700.二叉搜索树中的搜索.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 1521514a..fd1d21ac 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -200,7 +200,7 @@ class Solution { if (val < root.val) root = root.left; else if (val > root.val) root = root.right; else return root; - return root; + return null; } } ``` @@ -236,7 +236,7 @@ class Solution: if val < root.val: root = root.left elif val > root.val: root = root.right else: return root - return root + return None ``` @@ -271,7 +271,7 @@ func searchBST(root *TreeNode, val int) *TreeNode { break } } - return root + return nil } ``` @@ -301,7 +301,6 @@ var searchBST = function (root, val) { return searchBST(root.left, val); if (root.val < val) return searchBST(root.right, val); - return null; }; ``` @@ -330,7 +329,7 @@ var searchBST = function (root, val) { else return root; } - return root; + return null; }; ``` From 4b1542f8643f63ca9a09103642c680e05996e1a8 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 28 Feb 2022 21:02:53 +0800 Subject: [PATCH 25/38] =?UTF-8?q?1002=E6=9F=A5=E6=89=BE=E5=B8=B8=E7=94=A8?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E6=B7=BB=E5=8A=A0typescript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 7c5566d3..e3d4d774 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -253,6 +253,41 @@ var commonChars = function (words) { return res }; ``` +TypeScript +```ts + console.time("test") + let str: string = "" + //设置一个用字母组成的map字典 + let map = new Map() + //给所有map设置初始值为0 + let wordInitial: [string, number][] = words[0] + .split("") + .map((item) => [item, 0]) + //如果有重复字母,就把重复字母的数量加1 + for (let word of words[0]) { + map.set(word, map.has(word) ? map.get(word) + 1 : 1) + } + for (let i = 1; i < words.length; i++) { + const mapWord = new Map(wordInitial) + for (let j = 0; j < words[i].length; j++) { + if (!map.has(words[i][j])) continue + //mapWord中的字母的个数不能高于当前map的个数,多于则不能添加 + if (map.get(words[i][j]) > mapWord.get(words[i][j])) { + mapWord.set( + words[i][j], + mapWord.has(words[i][j]) ? mapWord!.get(words[i][j]) + 1 : 1 + ) + } + } + //每次重新初始化map + map = mapWord + } + for (let [key, value] of map) { + str += key.repeat(value) + } + console.timeEnd("test") + return str.split("") +``` GO ```golang func commonChars(words []string) []string { From fc5b272bd604dfe409a5c699d8253fde515b83ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BC=97=E8=B1=AA?= Date: Tue, 1 Mar 2022 08:56:51 +0800 Subject: [PATCH 26/38] =?UTF-8?q?fix:=200053.=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=92=20js=E4=BB=A3=E7=A0=81=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和(动态规划).md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index 37de9bbe..703e1dd6 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -174,6 +174,7 @@ const maxSubArray = nums => { // 数组长度,dp初始化 const len = nums.length; let dp = new Array(len).fill(0); + dp[0] = nums[0]; // 最大值初始化为dp[0] let max = dp[0]; for (let i = 1; i < len; i++) { From 66c3aab86a1c979ca14244c65ee2564be6e288d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8F=82=E7=8F=82?= Date: Tue, 1 Mar 2022 11:27:42 +0800 Subject: [PATCH 27/38] =?UTF-8?q?=E5=AF=B9=E4=BA=8E09=E8=BF=99=E6=A0=B7?= =?UTF-8?q?=E7=9A=84=E5=88=A4=E6=96=AD=E5=8F=AF=E4=BB=A5=E4=B8=8D=E5=81=9A?= =?UTF-8?q?=EF=BC=8C=E7=9B=B4=E6=8E=A5=E7=94=A8String.valueOf=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=B0=B1=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0738.单调递增的数字.md | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index e670bb31..c8ce8a2b 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -148,23 +148,19 @@ java版本1中创建了String数组,多次使用Integer.parseInt了方法, 版本2 class Solution { public int monotoneIncreasingDigits(int n) { - if (n==0)return 0; - char[] chars= Integer.toString(n).toCharArray(); - int start=Integer.MAX_VALUE;//start初始值设为最大值,这是为了防止当数字本身是单调递增时,没有一位数字需要改成9的情况 - for (int i=chars.length-1;i>0;i--){ - if (chars[i]= 0; i--) { + if (chars[i] > chars[i + 1]) { + chars[i]--; + start = i+1; } } - StringBuilder res=new StringBuilder(); - for (int i=0;i=start){ - res.append('9'); - }else res.append(chars[i]); + for (int i = start; i < s.length(); i++) { + chars[i] = '9'; } - return Integer.parseInt(res.toString()); + return Integer.parseInt(String.valueOf(chars)); } } ``` From e67bf9d4330aa3c7cf08f899aef2b11b3bba8cb8 Mon Sep 17 00:00:00 2001 From: Dawn-private <404232992@qq.com> Date: Tue, 1 Mar 2022 19:51:18 +0800 Subject: [PATCH 28/38] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF=E4=B8=8A?= =?UTF-8?q?=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改300.最长递增子序列动态数组的定义 --- problems/0300.最长上升子序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index ed61a30e..dfdd5125 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -37,7 +37,7 @@ 1. dp[i]的定义 -**dp[i]表示i之前包括i的最长上升子序列的长度**。 +**dp[i]表示i之前包括i的以nums[i]结尾最长上升子序列的长度** 2. 状态转移方程 From 10c49296ff3b7d9d97fd1d061beb8db77e771be9 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 1 Mar 2022 21:28:59 +0800 Subject: [PATCH 29/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880236.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=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=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0236.二叉树的最近公共祖先.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 6213aeaa..ca5fba77 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -325,6 +325,20 @@ var lowestCommonAncestor = function(root, p, q) { }; ``` +## TypeScript + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + if (root === null || root === p || root === q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (left !== null && right !== null) return root; + if (left !== null) return left; + if (right !== null) return right; + return null; +}; +``` + ----------------------- From d4e3da4c3db7729441397b7555b5a26b62fb8e2c Mon Sep 17 00:00:00 2001 From: Qiyu Liang <61932152+Guicai996@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:33:54 +0800 Subject: [PATCH 30/38] =?UTF-8?q?Update=200139.=E5=8D=95=E8=AF=8D=E6=8B=86?= =?UTF-8?q?=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除原Line 102,修改memory数组为bool型 因为根据执行顺序,Line 101的if判断句,只有在前一个判断返回true的时候才会递归,因此若执行到memory[startIndex] = 1时,程序已经完成了遍历,memory[startIndex] = 1的情况完全没用的上。而memory用上的情况为false重复,即程序已经判断过startIndex开头无法分割。 --- problems/0139.单词拆分.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 1653a81a..e04cb173 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -89,27 +89,26 @@ class Solution { private: bool backtracking (const string& s, const unordered_set& wordSet, - vector& memory, + vector& memory, int startIndex) { if (startIndex >= s.size()) { return true; } // 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果 - if (memory[startIndex] != -1) return memory[startIndex]; + if (!memory[startIndex]) return memory[startIndex]; for (int i = startIndex; i < s.size(); i++) { string word = s.substr(startIndex, i - startIndex + 1); if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) { - memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的 return true; } } - memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的 + memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的 return false; } public: bool wordBreak(string s, vector& wordDict) { unordered_set wordSet(wordDict.begin(), wordDict.end()); - vector memory(s.size(), -1); // -1 表示初始化状态 + vector memory(s.size(), 1); // -1 表示初始化状态 return backtracking(s, wordSet, memory, 0); } }; From 58ffbd146ba7250eba350b688f2bed095495e012 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:40:17 +0800 Subject: [PATCH 31/38] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200116.=E5=A1=AB?= =?UTF-8?q?=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87?= =?UTF-8?q?=E9=92=88.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index bc3a8c6b..2c443de5 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -211,9 +211,52 @@ class Solution: return root ``` ## Go - ```go - +// 迭代法 +func connect(root *Node) *Node { + if root == nil { + return root + } + stack := make([]*Node, 0) + stack = append(stack, root) + for len(stack) > 0 { + n := len(stack) // 记录当前层节点个数 + for i := 0; i < n; i++ { + node := stack[0] // 依次弹出节点 + stack = stack[1:] + if i == n - 1 { // 如果是这层最右的节点,next指向nil + node.Next = nil + } else { + node.Next = stack[0] // 如果不是最右的节点,next指向右边的节点 + } + if node.Left != nil { // 如果存在左子节点,放入栈中 + stack = append(stack, node.Left) + } + if node.Right != nil { // 如果存在右子节点,放入栈中 + stack = append(stack, node.Right) + } + } + } + return root +} +``` +```go +// 常量级额外空间,使用next +func connect(root *Node) *Node { + if root == nil { + return root + } + for cur := root; cur.Left != nil; cur = cur.Left { // 遍历每层最左边的节点 + for node := cur; node != nil; node = node.Next { // 当前层从左到右遍历 + node.Left.Next = node.Right // 左子节点next指向右子节点 + if node.Next != nil { //如果node next有值,右子节点指向next节点的左子节点 + node.Right.Next = node.Next.Left + } + + } + } + return root +} ``` ## JavaScript From 246bbe921c5a09cc0f440bb97a75cf92067fd950 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 2 Mar 2022 14:20:44 +0800 Subject: [PATCH 32/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880235.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b9d0a0bf..f7f1427a 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -350,6 +350,39 @@ var lowestCommonAncestor = function(root, p, q) { }; ``` +## TypeScript + +> 递归法: + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + if (root.val > p.val && root.val > q.val) + return lowestCommonAncestor(root.left, p, q); + if (root.val < p.val && root.val < q.val) + return lowestCommonAncestor(root.right, p, q); + return root; +}; +``` + +> 迭代法: + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + while (root !== null) { + if (root.val > p.val && root.val > q.val) { + root = root.left; + } else if (root.val < p.val && root.val < q.val) { + root = root.right; + } else { + return root; + }; + }; + return null; +}; +``` + + + -----------------------
From 32c54b4a5604aecab1681a84a8a58ed29b9a1151 Mon Sep 17 00:00:00 2001 From: Wayne <3522373084@qq.com> Date: Wed, 2 Mar 2022 16:03:14 +0800 Subject: [PATCH 33/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20968=20=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E4=BA=8C=E5=8F=89=E6=A0=91=20Java=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81,=E5=A2=9E=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0968.监控二叉树.md | 50 +++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 433060a5..35c3ccdc 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -316,28 +316,44 @@ public: ### Java ```java class Solution { - private int count = 0; + int res=0; public int minCameraCover(TreeNode root) { - if (trval(root) == 0) count++; - return count; + // 对根节点的状态做检验,防止根节点是无覆盖状态 . + if(minCame(root)==0){ + res++; + } + return res; } - - private int trval(TreeNode root) { - if (root == null) return -1; - - int left = trval(root.left); - int right = trval(root.right); - - if (left == 0 || right == 0) { - count++; + /** + 节点的状态值: + 0 表示无覆盖 + 1 表示 有摄像头 + 2 表示有覆盖 + 后序遍历,根据左右节点的情况,来判读 自己的状态 + */ + public int minCame(TreeNode root){ + if(root==null){ + // 空节点默认为 有覆盖状态,避免在叶子节点上放摄像头 return 2; } - - if (left == 2 || right == 2) { + int left=minCame(root.left); + int right=minCame(root.right); + + // 如果左右节点都覆盖了的话, 那么本节点的状态就应该是无覆盖,没有摄像头 + if(left==2&&right==2){ + //(2,2) + return 0; + }else if(left==0||right==0){ + // 左右节点都是无覆盖状态,那 根节点此时应该放一个摄像头 + // (0,0) (0,1) (0,2) (1,0) (2,0) + // 状态值为 1 摄像头数 ++; + res++; return 1; + }else{ + // 左右节点的 状态为 (1,1) (1,2) (2,1) 也就是左右节点至少存在 1个摄像头, + // 那么本节点就是处于被覆盖状态 + return 2; } - - return 0; } } ``` @@ -391,7 +407,7 @@ class Solution: result += 1 return result -``` +``` ### Go ```go From f4b55a1e4abb3e0ac0ae49c8126ee6a827c19447 Mon Sep 17 00:00:00 2001 From: ashing Date: Wed, 2 Mar 2022 21:10:26 +0800 Subject: [PATCH 34/38] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=A4=9A=E9=87=8D?= =?UTF-8?q?=E8=83=8C=E5=8C=85.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充 go 多重背包理论 --- .../背包问题理论基础多重背包.md | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md index 80b9f8a1..d05c3445 100644 --- a/problems/背包问题理论基础多重背包.md +++ b/problems/背包问题理论基础多重背包.md @@ -245,7 +245,94 @@ if __name__ == '__main__': Go: +```go +package theory +import "log" + +// 多重背包可以化解为 01 背包 +func multiplePack(weight, value, nums []int, bagWeight int) int { + + for i := 0; i < len(nums); i++ { + for nums[i] > 1 { + weight = append(weight, weight[i]) + value = append(value, value[i]) + nums[i]-- + } + } + log.Println(weight) + log.Println(value) + + res := make([]int, bagWeight+1) + for i := 0; i < len(weight); i++ { + for j := bagWeight; j >= weight[i]; j-- { + res[j] = getMax(res[j], res[j-weight[i]]+value[i]) + } + log.Println(res) + } + + return res[bagWeight] +} +``` + +> 单元测试 + +```go +package theory + +import "testing" + +func Test_multiplePack(t *testing.T) { + type args struct { + weight []int + value []int + nums []int + bagWeight int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "one", + args: args{ + weight: []int{1, 3, 4}, + value: []int{15, 20, 30}, + nums: []int{2, 3, 2}, + bagWeight: 10, + }, + want: 90, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := multiplePack(tt.args.weight, tt.args.value, tt.args.nums, tt.args.bagWeight); got != tt.want { + t.Errorf("multiplePack() = %v, want %v", got, tt.want) + } + }) + } +} +``` + +> 输出 + +``` +=== RUN Test_multiplePack +=== RUN Test_multiplePack/one +2022/03/02 21:09:05 [1 3 4 1 3 3 4] +2022/03/02 21:09:05 [15 20 30 15 20 20 30] +2022/03/02 21:09:05 [0 15 15 15 15 15 15 15 15 15 15] +2022/03/02 21:09:05 [0 15 15 20 35 35 35 35 35 35 35] +2022/03/02 21:09:05 [0 15 15 20 35 45 45 50 65 65 65] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 65 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 90] +--- PASS: Test_multiplePack (0.00s) + --- PASS: Test_multiplePack/one (0.00s) +PASS +``` ----------------------- From f2c75c27af3bd0ed9881faaa820529730068e353 Mon Sep 17 00:00:00 2001 From: kinsozheng Date: Wed, 2 Mar 2022 22:25:00 +0800 Subject: [PATCH 35/38] =?UTF-8?q?=E4=BF=AE=E6=94=B90018=E5=9B=9B=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20Python=E7=89=88=E6=9C=AC=20=E5=93=88?= =?UTF-8?q?=E5=B8=8C=E8=A1=A8=E6=B3=95=E8=A7=A3=E6=B3=95=20=E8=A7=A3?= =?UTF-8?q?=E5=86=B3=E7=94=A8set()=E5=AD=98=E5=82=A8=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E4=BD=86=E6=98=AF=E6=B5=8B=E8=AF=95=E6=8A=A5?= =?UTF-8?q?=E9=94=99=E7=9A=84=E9=97=AE=E9=A2=98=20=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E5=8A=A0=E5=85=A5=E4=BB=A5list()=E5=AD=98=E5=82=A8=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E7=9A=84=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index bad258c1..348f2f73 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -212,6 +212,7 @@ class Solution(object): # good thing about using python is you can use set to drop duplicates. ans = set() + # ans = [] # save results by list() for i in range(len(nums)): for j in range(i + 1, len(nums)): for k in range(j + 1, len(nums)): @@ -220,10 +221,16 @@ class Solution(object): # make sure no duplicates. count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val) if hashmap[val] > count: - ans.add(tuple(sorted([nums[i], nums[j], nums[k], val]))) - else: - continue - return ans + ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val])) + ans.add(ans_tmp) + # Avoiding duplication in list manner but it cause time complexity increases + # if ans_tmp not in ans: + # ans.append(ans_tmp) + else: + continue + return list(ans) + # if used list() to save results, just + # return ans ``` From 70ea2c76eab540df65f34f79f5ba425ba50c54c7 Mon Sep 17 00:00:00 2001 From: wangming Date: Thu, 3 Mar 2022 16:29:41 +0800 Subject: [PATCH 36/38] =?UTF-8?q?=E6=B7=BB=E5=8A=A00309.=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=9Fjs=E7=A9=BA=E9=97=B4=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...309.最佳买卖股票时机含冷冻期.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 2dc1e874..bb8909cd 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -284,6 +284,24 @@ const maxProfit = (prices) => { }; ``` +```javascript +// 一维数组空间优化 +const maxProfit = (prices) => { + const n = prices.length + const dp = new Array(4).fill(0) + dp[0] = -prices[0] + for (let i = 1; i < n; i ++) { + const temp = dp[0] // 缓存上一次的状态 + const temp1 = dp[2] + dp[0] = Math.max(dp[0], Math.max(dp[3] - prices[i], dp[1] - prices[i])) // 持有状态 + dp[1] = Math.max(dp[1], dp[3]) // 今天不操作且不持有股票 + dp[2] = temp + prices[i] // 今天卖出股票 + dp[3] = temp1 // 冷冻期 + } + return Math.max(...dp) +}; +``` + -----------------------
From d701e5e2aa80d44a24fbc54e241d6589e34d4b12 Mon Sep 17 00:00:00 2001 From: Wayne <3522373084@qq.com> Date: Sat, 5 Mar 2022 10:59:03 +0800 Subject: [PATCH 37/38] =?UTF-8?q?=E4=BF=AE=E6=94=B9739=20=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=E6=B8=A9=E5=BA=A6=E7=9A=84=20Java=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81,=E5=B9=B6=E5=A2=9E=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0739.每日温度.md | 76 +++++++++++++++++++++++------------ 1 file changed, 51 insertions(+), 25 deletions(-) diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index d7489028..bdc75b96 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -177,34 +177,60 @@ public: Java: ```java -/** - * 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到小 - *

- * 入站元素要和当前栈内栈首元素进行比较 - * 若大于栈首则 则与元素下标做差 - * 若大于等于则放入 - * - * @param temperatures - * @return - */ - public static int[] dailyTemperatures(int[] temperatures) { - Stack stack = new Stack<>(); - int[] res = new int[temperatures.length]; - for (int i = 0; i < temperatures.length; i++) { - /** - * 取出下标进行元素值的比较 - */ - while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { - int preIndex = stack.pop(); - res[preIndex] = i - preIndex; + +class Solution { + // 版本 1 + public int[] dailyTemperatures(int[] temperatures) { + + int lens=temperatures.length; + int []res=new int[lens]; + + /** + 如果当前遍历的元素 大于栈顶元素,表示 栈顶元素的 右边的最大的元素就是 当前遍历的元素, + 所以弹出 栈顶元素,并记录 + 如果栈不空的话,还要考虑新的栈顶与当前元素的大小关系 + 否则的话,可以直接入栈。 + 注意,单调栈里 加入的元素是 下标。 + */ + Stackstack=new Stack<>(); + stack.push(0); + for(int i=1;itemperatures[stack.peek()]){ + res[stack.peek()]=i-stack.peek(); + stack.pop(); + } + stack.push(i); } - /** - * 注意 放入的是元素位置 - */ - stack.push(i); } - return res; + + return res; } + + //--------这 是一条分界线 + // 版本 2 + class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int lens=temperatures.length; + int []res=new int[lens]; + Stackstack=new Stack<>(); + for(int i=0;itemperatures[stack.peek()]){ + res[stack.peek()]=i-stack.peek(); + stack.pop(); + } + stack.push(i); + } + + return res; + } +} + +} ``` Python: ``` Python3 From 6e3f394893c39edae8864fffc71eee986e81361f Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Mon, 7 Mar 2022 00:33:30 +0800 Subject: [PATCH 38/38] Add level order traversal --- problems/0101.对称二叉树.md | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index e4e232c8..0007b4d4 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -437,6 +437,41 @@ class Solution: return True ``` +层序遍历 + +```python +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if not root: return True + que, cnt = [[root.left, root.right]], 1 + while que: + nodes, tmp, sign = que.pop(), [], False + for node in nodes: + if not node: + tmp.append(None) + tmp.append(None) + else: + if node.left: + tmp.append(node.left) + sign = True + else: + tmp.append(None) + if node.right: + tmp.append(node.right) + sign = True + else: + tmp.append(None) + p1, p2 = 0, len(nodes) - 1 + while p1 < p2: + if (not nodes[p1] and nodes[p2]) or (nodes[p1] and not nodes[p2]): return False + elif nodes[p1] and nodes[p2] and nodes[p1].val != nodes[p2].val: return False + p1 += 1 + p2 -= 1 + if sign: que.append(tmp) + cnt += 1 + return True +``` + ## Go ```go