From f2a1ad632f99c6f1a37ab4b88310e2c03f7a8c52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B2=89=E9=BB=98?= <71065161+chenmo1995@users.noreply.github.com> Date: Thu, 30 Dec 2021 14:32:20 +0800 Subject: [PATCH 01/35] =?UTF-8?q?Update=200222.=E5=AE=8C=E5=85=A8=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9=E4=B8=AA=E6=95=B0?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0222.完全二叉树的节点个数.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index c5039039..754a6094 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -80,7 +80,7 @@ return treeNum; class Solution { private: int getNodesNum(TreeNode* cur) { - if (cur == 0) return 0; + if (cur == NULL) return 0; int leftNum = getNodesNum(cur->left); // 左 int rightNum = getNodesNum(cur->right); // 右 int treeNum = leftNum + rightNum + 1; // 中 From 4ed7da80c08a51cc79cbc0aa987d41f6a57da5fe Mon Sep 17 00:00:00 2001 From: Steve <841532108@qq.com> Date: Fri, 31 Dec 2021 16:18:03 +0800 Subject: [PATCH 02/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE.md=20Typescript=20=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/0704.二分查找.md | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 689c0633..cc7d7de5 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -326,6 +326,46 @@ var search = function(nums, target) { }; ``` +**TypeScript** + +(版本一)左闭右闭区间 + +```typescript +function search(nums: number[], target: number): number { + let left: number = 0, right: number = nums.length - 1; + while (left <= right) { + let mid: number = left + Math.floor((right - left) / 2); + if (nums[mid] > target) { + right = mid - 1; + } else if (nums[mid] < target) { + left = mid + 1; + } else { + return mid; + } + } + return -1; +}; +``` + +(版本二)左闭右开区间 + +```typescript +function search(nums: number[], target: number): number { + let left: number = 0, right: number = nums.length; + while (left < right) { + let mid: number = left + Math.floor((right - left) / 2); + if (nums[mid] > target) { + right = mid; + } else if (nums[mid] < target) { + left = mid + 1; + } else { + return mid; + } + } + return -1; +}; +``` + **Ruby:** ```ruby From 0dbd6c42d249cf0a33bdcd9a2f67c023f83003f1 Mon Sep 17 00:00:00 2001 From: Steve <841532108@qq.com> Date: Fri, 31 Dec 2021 16:29:05 +0800 Subject: [PATCH 03/35] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200704.=E4=BA=8C?= =?UTF-8?q?=E5=88=86=E6=9F=A5=E6=89=BE.md=EF=BC=9A=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E5=A4=9A=E4=BD=99=E5=AD=97=E7=AC=A6=EF=BC=8C=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=9C=AA=E9=AB=98=E4=BA=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index cc7d7de5..379cb5fc 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -284,7 +284,6 @@ func search(nums []int, target int) int { * @param {number} target * @return {number} */ -/** var search = function(nums, target) { let left = 0, right = nums.length - 1; // 使用左闭右闭区间 From d58fe4ea60f314dd4a9ffdd41beadc4710369ba7 Mon Sep 17 00:00:00 2001 From: Kai Dang <15596570256@163.com> Date: Fri, 31 Dec 2021 17:04:46 +0800 Subject: [PATCH 04/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200040.=E7=BB=84?= =?UTF-8?q?=E5=90=88=E6=80=BB=E5=92=8CII.md=20=E4=B8=AD=E7=9A=84Java?= =?UTF-8?q?=E4=B8=8EGo=E7=9A=84=E4=B8=8D=E4=BD=BF=E7=94=A8=E6=A0=87?= =?UTF-8?q?=E8=AE=B0=E6=95=B0=E7=BB=84=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 76 ++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 31011ed6..5d9e4965 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -255,6 +255,7 @@ public: ## Java +**使用标记数组** ```Java class Solution { List> lists = new ArrayList<>(); @@ -292,6 +293,44 @@ class Solution { } } ``` +**不使用标记数组** +```Java +class Solution { + List> res = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + int sum = 0; + + public List> combinationSum2( int[] candidates, int target ) { + //为了将重复的数字都放到一起,所以先进行排序 + Arrays.sort( candidates ); + backTracking( candidates, target, 0 ); + return res; + } + + private void backTracking( int[] candidates, int target, int start ) { + if ( sum == target ) { + res.add( new ArrayList<>( path ) ); + return; + } + for ( int i = start; i < candidates.length && sum + candidates[i] <= target; i++ ) { + //正确剔除重复解的办法 + //跳过同一树层使用过的元素 + if ( i > start && candidates[i] == candidates[i - 1] ) { + continue; + } + + sum += candidates[i]; + path.add( candidates[i] ); + // i+1 代表当前组内元素只选取一次 + backTracking( candidates, target, i + 1 ); + + int temp = path.getLast(); + sum -= temp; + path.removeLast(); + } + } +} +``` ## Python **回溯+巧妙去重(省去使用used** @@ -384,6 +423,7 @@ class Solution: ## Go 主要在于如何在回溯中去重 +**使用used数组** ```go func combinationSum2(candidates []int, target int) [][]int { var trcak []int @@ -423,7 +463,41 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int, } } ``` - +**不使用used数组** +```go +func combinationSum2(candidates []int, target int) [][]int { + var trcak []int + var res [][]int + sort.Ints(candidates) + backtracking(0,0,target,candidates,trcak,&res) + return res +} +func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int){ + //终止条件 + if sum==target{ + tmp:=make([]int,len(trcak)) + //拷贝 + copy(tmp,trcak) + //放入结果集 + *res=append(*res,tmp) + return + } + //回溯 + for i:=startIndex;istartIndex&&candidates[i]==candidates[i-1]{ + continue + } + //更新路径集合和sum + trcak=append(trcak,candidates[i]) + sum+=candidates[i] + backtracking(i+1,sum,target,candidates,trcak,res) + //回溯 + trcak=trcak[:len(trcak)-1] + sum-=candidates[i] + } +} +``` ## javaScript ```js From e894f44b607b0a3433cae8284a9e2c0c85f86645 Mon Sep 17 00:00:00 2001 From: Steve <841532108@qq.com> Date: Fri, 31 Dec 2021 19:23:47 +0800 Subject: [PATCH 05/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880027.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E5=85=83=E7=B4=A0.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=20typescript=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 693684f3..99990302 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -197,7 +197,23 @@ var removeElement = (nums, val) => { }; ``` +TypeScript: + +```typescript +function removeElement(nums: number[], val: number): number { + let slowIndex: number = 0, fastIndex: number = 0; + while (fastIndex < nums.length) { + if (nums[fastIndex] !== val) { + nums[slowIndex++] = nums[fastIndex]; + } + fastIndex++; + } + return slowIndex; +}; +``` + Ruby: + ```ruby def remove_element(nums, val) i = 0 From 2e16036f1abcd6a42b4f0dc66f402fd0ddf0cd78 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 31 Dec 2021 20:16:20 +0800 Subject: [PATCH 06/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880977.=E6=9C=89?= =?UTF-8?q?=E5=BA=8F=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E6=B7=BB=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/0977.有序数组的平方.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 0085de0b..b11fa7ef 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -221,6 +221,35 @@ var sortedSquares = function(nums) { }; ``` +Typescript: + +双指针法: + +```typescript +function sortedSquares(nums: number[]): number[] { + let left: number = 0, right: number = nums.length - 1; + let resArr: number[] = new Array(nums.length); + let resArrIndex: number = resArr.length - 1; + while (left <= right) { + if (Math.abs(nums[left]) < Math.abs(nums[right])) { + resArr[resArrIndex] = nums[right--] ** 2; + } else { + resArr[resArrIndex] = nums[left++] ** 2; + } + resArrIndex--; + } + return resArr; +}; +``` + +骚操作法(暴力思路): + +```typescript +function sortedSquares(nums: number[]): number[] { + return nums.map(i => i * i).sort((a, b) => a - b); +}; +``` + Swift: ```swift From 082302078bd1e4a354f21a4b8f77a9a6b389940b Mon Sep 17 00:00:00 2001 From: tlylt Date: Sat, 1 Jan 2022 11:17:07 +0800 Subject: [PATCH 07/35] fix Qn0077 python indent --- problems/0077.组合.md | 2 +- problems/0077.组合优化.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 4ec154e1..c00f1efb 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -422,7 +422,7 @@ class Solution: def backtrack(n,k,startIndex): if len(path) == k: res.append(path[:]) - return + return for i in range(startIndex,n - (k - len(path)) + 2): #优化的地方 path.append(i) #处理节点 backtrack(n,k,i+1) #递归 diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 5fe56e82..4eec1608 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -182,7 +182,7 @@ class Solution: def backtrack(n,k,startIndex): if len(path) == k: res.append(path[:]) - return + return for i in range(startIndex,n-(k-len(path))+2): #优化的地方 path.append(i) #处理节点 backtrack(n,k,i+1) #递归 From eb94c291b26f43470d874a405b78c914d3bdb9c3 Mon Sep 17 00:00:00 2001 From: tlylt Date: Sat, 1 Jan 2022 11:38:38 +0800 Subject: [PATCH 08/35] fix Qn0077 & Qn0216 python indent errors --- problems/0077.组合.md | 4 ++-- problems/0077.组合优化.md | 4 ++-- problems/0216.组合总和III.md | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index c00f1efb..c00ff551 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -427,8 +427,8 @@ class Solution: path.append(i) #处理节点 backtrack(n,k,i+1) #递归 path.pop() #回溯,撤销处理的节点 - backtrack(n,k,1) - return res + backtrack(n,k,1) + return res ``` diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 4eec1608..24bfc086 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -187,8 +187,8 @@ class Solution: path.append(i) #处理节点 backtrack(n,k,i+1) #递归 path.pop() #回溯,撤销处理的节点 - backtrack(n,k,1) - return res + backtrack(n,k,1) + return res ``` Go: ```Go diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 26c630b9..0bb42192 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -323,7 +323,6 @@ class Solution: self.backtracking(k, n, i + 1) self.path.pop() self.sum_now -= i - return ``` ## Go From f4ea34989e8a114259a5a9ca5501d831101e8475 Mon Sep 17 00:00:00 2001 From: joeCarf <52153761+joeCarf@users.noreply.github.com> Date: Sat, 1 Jan 2022 23:08:04 +0800 Subject: [PATCH 09/35] =?UTF-8?q?[+]=20LeetCode=2028:=E5=89=8D=E7=BC=80?= =?UTF-8?q?=E8=A1=A8=EF=BC=88=E4=B8=8D=E5=87=8F=E4=B8=80=EF=BC=89Java?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index ef7008bc..f0b56719 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -649,6 +649,41 @@ class Solution { } ``` +```Java +class Solution { + //前缀表(不减一)Java实现 + public int strStr(String haystack, String needle) { + if (needle.length() == 0) return 0; + int[] next = new int[needle.length()]; + getNext(next, needle); + + int j = 0; + for (int i = 0; i < haystack.length(); i++) { + while (j > 0 && needle.charAt(j) != haystack.charAt(i)) + j = next[j - 1]; + if (needle.charAt(j) == haystack.charAt(i)) + j++; + if (j == needle.length()) + return i - needle.length() + 1; + } + return -1; + + } + + private void getNext(int[] next, String s) { + int j = 0; + next[0] = 0; + for (int i = 1; i < s.length(); i++) { + while (j > 0 && s.charAt(j) != s.charAt(i)) + j = next[j - 1]; + if (s.charAt(j) == s.charAt(i)) + j++; + next[i] = j; + } + } +} +``` + Python3: ```python From 46ceb72cd01b08f6a734ca87d329c56ec51a51e6 Mon Sep 17 00:00:00 2001 From: erdengk <15596570256@163.com> Date: Sun, 2 Jan 2022 11:21:56 +0800 Subject: [PATCH 10/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200090.=E5=AD=90?= =?UTF-8?q?=E9=9B=86II.md=20=E4=B8=AD=E7=9A=84Java=E4=B8=8D=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=A0=87=E8=AE=B0=E6=95=B0=E7=BB=84=E7=9A=84=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/0090.子集II.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 5b92517a..a1e86464 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -166,7 +166,7 @@ if (i > startIndex && nums[i] == nums[i - 1] ) { ### Java - +使用used数组 ```java class Solution { List> result = new ArrayList<>();// 存放符合条件结果的集合 @@ -202,6 +202,37 @@ class Solution { } ``` +不使用used数组 +```java +class Solution { + + List> res = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + + public List> subsetsWithDup( int[] nums ) { + Arrays.sort( nums ); + subsetsWithDupHelper( nums, 0 ); + return res; + } + + + private void subsetsWithDupHelper( int[] nums, int start ) { + res.add( new ArrayList<>( path ) ); + + for ( int i = start; i < nums.length; i++ ) { + // 跳过当前树层使用过的、相同的元素 + if ( i > start && nums[i - 1] == nums[i] ) { + continue; + } + path.add( nums[i] ); + subsetsWithDupHelper( nums, i + 1 ); + path.removeLast(); + } + } + +} +``` + ### Python ```python class Solution: From 4e2c449827e3bc6a7b2e9c52803076118314f6b3 Mon Sep 17 00:00:00 2001 From: reoooh Date: Sun, 2 Jan 2022 22:36:47 +0800 Subject: [PATCH 11/35] 2022-0102: 0209 add ruby version --- problems/0209.长度最小的子数组.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 80822436..7c13961d 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -107,7 +107,7 @@ public: }; ``` -时间复杂度:$O(n)$ +时间复杂度:$O(n)$ 空间复杂度:$O(1)$ **一些录友会疑惑为什么时间复杂度是$O(n)$**。 @@ -121,7 +121,6 @@ public: - ## 其他语言版本 @@ -291,5 +290,23 @@ class Solution { } ``` +Ruby: + +```ruby +def min_sub_array_len(target, nums) + res = Float::INFINITY # 无穷大 + i, sum = 0, 0 + nums.length.times do |j| + sum += nums[j] + while sum >= target + res = [res, j - i + 1].min + sum -= nums[i] + i += 1 + end + end + res == Float::INFINITY ? 0 : res +end +``` + -----------------------
From f6d8350d24d6d24561db7af26a123ea0101cf4ae Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 2 Jan 2022 23:24:52 +0800 Subject: [PATCH 12/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880209.=E9=95=BF?= =?UTF-8?q?=E5=BA=A6=E6=9C=80=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84?= =?UTF-8?q?.md=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/0209.长度最小的子数组.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 80822436..2c6ea775 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -214,6 +214,28 @@ var minSubArrayLen = function(target, nums) { }; ``` +Typescript: + +```typescript +function minSubArrayLen(target: number, nums: number[]): number { + let left: number = 0, right: number = 0; + let res: number = nums.length + 1; + let sum: number = 0; + while (right < nums.length) { + sum += nums[right]; + if (sum >= target) { + // 不断移动左指针,直到不能再缩小为止 + while (sum - nums[left] >= target) { + sum -= nums[left++]; + } + res = Math.min(res, right - left + 1); + } + right++; + } + return res === nums.length + 1 ? 0 : res; +}; +``` + Swift: ```swift From e3f88873f66c432c7571f5278a2db2e00a5d0a88 Mon Sep 17 00:00:00 2001 From: Frogrey <35210929+Frogrey@users.noreply.github.com> Date: Mon, 3 Jan 2022 15:44:28 +0800 Subject: [PATCH 13/35] =?UTF-8?q?309.=E6=9C=80=E4=BD=B3=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E6=97=B6=E6=9C=BA=E5=90=AB=E5=86=B7=E5=86=BB?= =?UTF-8?q?=E6=9C=9F=20=E9=80=92=E6=8E=A8=E4=BB=A3=E7=A0=81=E5=B0=91?= =?UTF-8?q?=E4=BA=86=E4=B8=80=E4=B8=AA=E6=8B=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0309.最佳买卖股票时机含冷冻期.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 82555f80..10cdd5fd 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -95,7 +95,7 @@ p[i][3] = dp[i - 1][2]; 综上分析,递推代码如下: ```CPP -dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3], dp[i - 1][1]) - prices[i]; +dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3], dp[i - 1][1]) - prices[i]); dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]); dp[i][2] = dp[i - 1][0] + prices[i]; dp[i][3] = dp[i - 1][2]; From b36f6755998b4ed3ca3e827e547bca95dce224da Mon Sep 17 00:00:00 2001 From: Dewittt <43514251+Dewittt@users.noreply.github.com> Date: Mon, 3 Jan 2022 15:56:46 +0800 Subject: [PATCH 14/35] =?UTF-8?q?Update=200347.=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 前k个,应该传入倒序的comparator --- problems/0347.前K个高频元素.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index e6ad751b..a2825573 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -142,7 +142,7 @@ class Solution { Set> entries = map.entrySet(); // 根据map的value值正序排,相当于一个小顶堆 - PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue()); for (Map.Entry entry : entries) { queue.offer(entry); if (queue.size() > k) { From 8399eed5204963a8968b7872cf4aa3c3ef486f8b Mon Sep 17 00:00:00 2001 From: Frogrey <35210929+Frogrey@users.noreply.github.com> Date: Mon, 3 Jan 2022 17:13:00 +0800 Subject: [PATCH 15/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20674.=20=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E8=BF=9E=E7=BB=AD=E9=80=92=E5=A2=9E=E5=BA=8F=E5=88=97?= =?UTF-8?q?=20Java=20=E8=B4=AA=E5=BF=83=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0674.最长连续递增序列.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 98e09bf8..51d04e92 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -154,6 +154,8 @@ public: Java: + +> 动态规划: ```java /** * 1.dp[i] 代表当前下标最大连续值 @@ -180,6 +182,25 @@ Java: } ``` +> 贪心法: + +```Java +public static int findLengthOfLCIS(int[] nums) { + if (nums.length == 0) return 0; + int res = 1; // 连续子序列最少也是1 + int count = 1; + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i + 1] > nums[i]) { // 连续记录 + count++; + } else { // 不连续,count从头开始 + count = 1; + } + if (count > res) res = count; + } + return res; +} +``` + Python: > 动态规划: From a828e5f247c8095171d60b74eefdbeb1a6b3a9a5 Mon Sep 17 00:00:00 2001 From: Martin Hsu <31008681+Martin-Hsu@users.noreply.github.com> Date: Tue, 4 Jan 2022 14:08:00 +0800 Subject: [PATCH 16/35] =?UTF-8?q?Update=200739.=E6=AF=8F=E6=97=A5=E6=B8=A9?= =?UTF-8?q?=E5=BA=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0739.每日温度.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index d025e73c..d7489028 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -119,7 +119,7 @@ C++代码如下: class Solution { public: vector dailyTemperatures(vector& T) { - // 递减栈 + // 递增栈 stack st; vector result(T.size(), 0); st.push(0); @@ -150,7 +150,7 @@ public: class Solution { public: vector dailyTemperatures(vector& T) { - stack st; // 递减栈 + stack st; // 递增栈 vector result(T.size(), 0); for (int i = 0; i < T.size(); i++) { while (!st.empty() && T[i] > T[st.top()]) { // 注意栈不能为空 @@ -178,7 +178,7 @@ public: Java: ```java /** - * 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到笑 + * 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到小 *

* 入站元素要和当前栈内栈首元素进行比较 * 若大于栈首则 则与元素下标做差 From 4b0460cdd3b198c99724c6ff93daaeb541a53bd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Wed, 5 Jan 2022 11:34:24 +0800 Subject: [PATCH 17/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20102.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 282 +++++++++++++++++++++- 1 file changed, 281 insertions(+), 1 deletion(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 4fcbbff8..1fb9b633 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -246,6 +246,34 @@ var levelOrder = function(root) { ``` +Swift: +```swift +func levelOrder(_ root: TreeNode?) -> [[Int]] { + var res = [[Int]]() + guard let root = root else { + return res + } + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + var sub = [Int]() + for _ in 0 ..< size { + let node = queue.removeFirst() + sub.append(node.val) + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + res.append(sub) + } + return res +} +``` + **此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!** @@ -426,6 +454,31 @@ var levelOrderBottom = function(root) { }; ``` +Swift: +```swift +func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { + var res = [[Int]]() + guard let root = root else { + return res + } + var queue: [TreeNode] = [root] + while !queue.isEmpty { + var sub = [Int]() + for _ in 0 ..< queue.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) + } + } + res.insert(sub, at: 0) + } + return res +} +``` # 199.二叉树的右视图 @@ -604,6 +657,36 @@ var rightSideView = function(root) { }; ``` +Swift: +```swift +func rightSideView(_ root: TreeNode?) -> [Int] { + var res = [Int]() + guard let root = root else { + return res + } + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + for i in 0 ..< size { + 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) + } + } + } + return res +} +``` + + # 637.二叉树的层平均值 [力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/) @@ -785,6 +868,34 @@ var averageOfLevels = function(root) { }; ``` +Swift: +```swift +func averageOfLevels(_ root: TreeNode?) -> [Double] { + var res = [Double]() + guard let root = root else { + return res + } + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + var sum = 0 + for _ in 0 ..< size { + let node = queue.removeFirst() + sum += node.val + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + res.append(Double(sum) / Double(size)) + } + return res +} +``` + # 429.N叉树的层序遍历 [力扣题目链接](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/) @@ -981,6 +1092,31 @@ var levelOrder = function(root) { }; ``` +Swift: +```swift +func levelOrder(_ root: Node?) -> [[Int]] { + var res = [[Int]]() + guard let root = root else { + return res + } + var queue = [Node]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + var sub = [Int]() + for _ in 0 ..< size { + let node = queue.removeFirst() + sub.append(node.val) + for childNode in node.children { + queue.append(childNode) + } + } + res.append(sub) + } + return res +} +``` + # 515.在每个树行中找最大值 [力扣题目链接](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/) @@ -1136,6 +1272,36 @@ var largestValues = function(root) { }; ``` +Swift: +```swift +func largestValues(_ root: TreeNode?) -> [Int] { + var res = [Int]() + guard let root = root else { + return res + } + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + var max: Int = Int.min + for _ in 0 ..< size { + 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) + } + } + res.append(max) + } + return res +} +``` + # 116.填充每个节点的下一个右侧节点指针 [力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/) @@ -1338,6 +1504,37 @@ func connect(root *Node) *Node { } ``` +Swift: +```swift +func connect(_ root: Node?) -> Node? { + guard let root = root else { + return nil + } + var queue = [Node]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + var preNode: Node? + for i in 0 ..< size { + let node = queue.removeFirst() + if i == 0 { + preNode = node + } else { + preNode?.next = node + preNode = node + } + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return root +} +``` + # 117.填充每个节点的下一个右侧节点指针II [力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/) @@ -1532,6 +1729,38 @@ 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) + while !queue.isEmpty { + let size = queue.count + var preNode: Node? + for i in 0 ..< size { + let node = queue.removeFirst() + if i == 0 { + preNode = node + } else { + preNode?.next = node + preNode = node + } + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return root +} +``` + # 104.二叉树的最大深度 [力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) @@ -1704,6 +1933,31 @@ var maxDepth = function(root) { }; ``` +Swift: +```swift +func maxDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var queue = [TreeNode]() + queue.append(root) + var res: Int = 0 + while !queue.isEmpty { + for _ in 0 ..< queue.count { + let node = queue.removeFirst() + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + res += 1 + } + return res +} +``` + # 111.二叉树的最小深度 [力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) @@ -1876,7 +2130,33 @@ var minDepth = function(root) { }; ``` - +Swift: +```swift +func minDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var res = 0 + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + res += 1 + for _ in 0 ..< queue.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) + } + } + } + return res +} +``` # 总结 From 5efb10740ed78aa75dfb89f81ab1db5be04f7b3d Mon Sep 17 00:00:00 2001 From: Hnuczc <3260189532@qq.com> Date: Wed, 5 Jan 2022 19:08:48 +0800 Subject: [PATCH 18/35] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E5=88=A4=E6=96=AD=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 39 ++++++++--------------- 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 7f7b2f4c..f44703f1 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -133,39 +133,26 @@ public: java: ```Java -public class EvalRPN { - +class Solution { public int evalRPN(String[] tokens) { Deque stack = new LinkedList(); - for (String token : tokens) { - char c = token.charAt(0); - if (!isOpe(token)) { - stack.addFirst(stoi(token)); - } else if (c == '+') { - stack.push(stack.pop() + stack.pop()); - } else if (c == '-') { - stack.push(- stack.pop() + stack.pop()); - } else if (c == '*') { - stack.push( stack.pop() * stack.pop()); + for (int i = 0; i < tokens.length; ++i) { + if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等 + stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理 + } else if ("-".equals(tokens[i])) { + stack.push(-stack.pop() + stack.pop()); + } else if ("*".equals(tokens[i])) { + stack.push(stack.pop() * stack.pop()); + } else if ("/".equals(tokens[i])) { + int temp1 = stack.pop(); + int temp2 = stack.pop(); + stack.push(temp2 / temp1); } else { - int num1 = stack.pop(); - int num2 = stack.pop(); - stack.push( num2/num1); + stack.push(Integer.valueOf(tokens[i])); } } return stack.pop(); } - private boolean isOpe(String s) { - return s.length() == 1 && s.charAt(0) <'0' || s.charAt(0) >'9'; - } - private int stoi(String s) { - return Integer.valueOf(s); - } - - public static void main(String[] args) { - new EvalRPN().evalRPN(new String[] {"10","6","9","3","+","-11","*","/","*","17","+","5","+"}); - } - } ``` From d28293da0c42ddf96599b3bdb022040fca548c62 Mon Sep 17 00:00:00 2001 From: YuYiming <41357594+Leovoki@users.noreply.github.com> Date: Wed, 5 Jan 2022 21:26:01 +0800 Subject: [PATCH 19/35] =?UTF-8?q?Update=200459.=E9=87=8D=E5=A4=8D=E7=9A=84?= =?UTF-8?q?=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 有些人使用的是从0开始的next数组不是从-1的,因此会疑惑。 --- problems/0459.重复的子字符串.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index fee9dee5..9c74f4a7 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -45,7 +45,7 @@ 这里就要说一说next数组了,next 数组记录的就是最长相同前后缀( [字符串:KMP算法精讲](https://programmercarl.com/0028.实现strStr.html) 这里介绍了什么是前缀,什么是后缀,什么又是最长相同前后缀), 如果 next[len - 1] != -1,则说明字符串有最长相同的前后缀(就是字符串里的前缀子串和后缀子串相同的最长长度)。 -最长相等前后缀的长度为:next[len - 1] + 1。 +最长相等前后缀的长度为:next[len - 1] + 1。(这里的next数组是以统一减一的方式计算的,因此需要+1) 数组长度为:len。 From 774c3da8309c468f3f12c28c8180fae6403a976d Mon Sep 17 00:00:00 2001 From: YiChih Wang Date: Wed, 5 Jan 2022 22:32:18 +0800 Subject: [PATCH 20/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200131.=E5=88=86?= =?UTF-8?q?=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2=20Rust=E8=AA=9E=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/0131.分割回文串.md | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index ec8ad61c..439ad8ea 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -587,5 +587,57 @@ func partition(_ s: String) -> [[String]] { } ``` +## Rust + +```rust +impl Solution { + pub fn partition(s: String) -> Vec> { + let mut ret = vec![]; + let mut path = vec![]; + let sub_str: Vec = s.chars().collect(); + + Self::backtracing(&sub_str, 0, &mut ret, &mut path); + + ret + } + + fn backtracing(sub_str: &Vec, start: usize, ret: &mut Vec>, path: &mut Vec) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + if start >= sub_str.len() { + ret.push(path.clone()); + return; + } + + for i in start..sub_str.len() { + if !Self::is_palindrome(sub_str, start, i) { + continue; + } + //如果是回文子串,则记录 + let s: String = sub_str[start..i+1].into_iter().collect(); + path.push(s); + + //起始位置后移,保证不重复 + Self::backtracing(sub_str, i+1, ret, path); + path.pop(); + } + + } + + fn is_palindrome(s: &Vec, start: usize, end: usize) -> bool { + let (mut start, mut end) = (start, end); + + while start < end { + if s[start] != s[end] { + return false; + } + + start += 1; + end -= 1; + } + + true + } +} +``` -----------------------

From 871ae8f6196114273320aa7db77817e6af559d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Thu, 6 Jan 2022 14:32:38 +0800 Subject: [PATCH 21/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20226.=E7=BF=BB?= =?UTF-8?q?=E8=BD=AC=E4=BA=8C=E5=8F=89=E6=A0=91=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index ee1f5ddf..e6dbb709 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -609,5 +609,43 @@ struct TreeNode* invertTree(struct TreeNode* root){ } ``` +### Swift: +```swift +// 前序遍历-递归 +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let root = root else { + return root + } + let tmp = root.left + root.left = root.right + root.right = tmp + let _ = invertTree(root.left) + let _ = invertTree(root.right) + return root +} + +// 层序遍历-迭代 +func invertTree1(_ root: TreeNode?) -> TreeNode? { + guard let root = root else { + return nil + } + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let node = queue.removeFirst() + let tmp = node.left + node.left = node.right + node.right = tmp + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + return root +} +``` + -----------------------
From 155f457d22a9a94fbcf21ebbf2d34c9769e8e32d Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Thu, 6 Jan 2022 15:07:39 +0000 Subject: [PATCH 22/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200047.=E5=85=A8?= =?UTF-8?q?=E6=8E=92=E5=88=97II.md=20C=E8=AF=AD=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/0047.全排列II.md | 71 ++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index 781f01c3..0cecac50 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -323,5 +323,76 @@ func permuteUnique(_ nums: [Int]) -> [[Int]] { } ``` +### C +```c +//临时数组 +int *path; +//返回数组 +int **ans; +int *used; +int pathTop, ansTop; + +//拷贝path到ans中 +void copyPath() { + int *tempPath = (int*)malloc(sizeof(int) * pathTop); + int i; + for(i = 0; i < pathTop; ++i) { + tempPath[i] = path[i]; + } + ans[ansTop++] = tempPath; +} + +void backTracking(int* used, int *nums, int numsSize) { + //若path中元素个数等于numsSize,将path拷贝入ans数组中 + if(pathTop == numsSize) + copyPath(); + int i; + for(i = 0; i < numsSize; i++) { + //若当前元素已被使用 + //或前一位元素与当前元素值相同但并未被使用 + //则跳过此分支 + if(used[i] || (i != 0 && nums[i] == nums[i-1] && used[i-1] == 0)) + continue; + + //将当前元素的使用情况设为True + used[i] = 1; + path[pathTop++] = nums[i]; + backTracking(used, nums, numsSize); + used[i] = 0; + --pathTop; + } +} + +int cmp(void* elem1, void* elem2) { + return *((int*)elem1) - *((int*)elem2); +} + +int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ + //排序数组 + qsort(nums, numsSize, sizeof(int), cmp); + //初始化辅助变量 + pathTop = ansTop = 0; + path = (int*)malloc(sizeof(int) * numsSize); + ans = (int**)malloc(sizeof(int*) * 1000); + //初始化used辅助数组 + used = (int*)malloc(sizeof(int) * numsSize); + int i; + for(i = 0; i < numsSize; i++) { + used[i] = 0; + } + + backTracking(used, nums, numsSize); + + //设置返回的数组的长度 + *returnSize = ansTop; + *returnColumnSizes = (int*)malloc(sizeof(int) * ansTop); + int z; + for(z = 0; z < ansTop; z++) { + (*returnColumnSizes)[z] = numsSize; + } + return ans; +} +``` + -----------------------
From 59b38a9ebf73af718de50c7cc11b92bc5ef0ad68 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 19 Dec 2021 17:04:04 +0800 Subject: [PATCH 23/35] =?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=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 08e7ec3d..7c5566d3 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -58,7 +58,7 @@ words[i] 由小写英文字母组成 先统计第一个字符串所有字符出现的次数,代码如下: -``` +```cpp int hash[26] = {0}; // 用来统计所有字符串里字符出现的最小频率 for (int i = 0; i < A[0].size(); i++) { // 用第一个字符串给hash初始化 hash[A[0][i] - 'a']++; @@ -71,7 +71,7 @@ for (int i = 0; i < A[0].size(); i++) { // 用第一个字符串给hash初始化 代码如下: -``` +```cpp int hashOtherStr[26] = {0}; // 统计除第一个字符串外字符的出现频率 for (int i = 1; i < A.size(); i++) { memset(hashOtherStr, 0, 26 * sizeof(int)); @@ -84,11 +84,11 @@ for (int i = 1; i < A.size(); i++) { } } ``` -此时hash里统计着字符在所有字符串里出现的最小次数,那么把hash转正题目要求的输出格式就可以了。 +此时hash里统计着字符在所有字符串里出现的最小次数,那么把hash转成题目要求的输出格式就可以了。 代码如下: -``` +```cpp // 将hash统计的字符次数,转成输出形式 for (int i = 0; i < 26; i++) { while (hash[i] != 0) { // 注意这里是while,多个重复的字符 From 3078fb8eeaaa0a7e4200e6a0c2eb5e7835ea5bb4 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 19 Dec 2021 17:22:04 +0800 Subject: [PATCH 24/35] =?UTF-8?q?0001.=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8C?= =?UTF-8?q?=EF=BC=9A=E7=AE=80=E5=8C=96Swift=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 37c95736..8551274c 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -207,18 +207,16 @@ function twoSum(array $nums, int $target): array Swift: ```swift func twoSum(_ nums: [Int], _ target: Int) -> [Int] { - var res = [Int]() - var dict = [Int : Int]() - for i in 0 ..< nums.count { - let other = target - nums[i] - if dict.keys.contains(other) { - res.append(i) - res.append(dict[other]!) - return res + // 值: 下标 + var map = [Int: Int]() + for (i, e) in nums.enumerated() { + if let v = map[target - e] { + return [v, i] + } else { + map[e] = i } - dict[nums[i]] = i } - return res + return [] } ``` From 6144420c3962f2e63a4e682baa5e7eecce10b08c Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 19 Dec 2021 17:28:51 +0800 Subject: [PATCH 25/35] =?UTF-8?q?0454.=E5=9B=9B=E6=95=B0=E7=9B=B8=E5=8A=A0?= =?UTF-8?q?II=EF=BC=9A=E7=AE=80=E5=8C=96Swift=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0454.四数相加II.md | 36 +++++++++++++++------------------ 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 6853354c..6e916608 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -44,7 +44,7 @@ D = [ 0, 2] 1. 首先定义 一个unordered_map,key放a和b两数之和,value 放a和b两数之和出现的次数。 2. 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中。 -3. 定义int变量count,用来统计a+b+c+d = 0 出现的次数。 +3. 定义int变量count,用来统计 a+b+c+d = 0 出现的次数。 4. 在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就用count把map中key对应的value也就是出现次数统计出来。 5. 最后返回统计值 count 就可以了 @@ -139,7 +139,7 @@ class Solution(object): return count -``` +``` Go: ```go @@ -229,28 +229,24 @@ class Solution { Swift: ```swift func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int { - // key:a+b的数值,value:a+b数值出现的次数 - var map = [Int: Int]() - // 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中 - for i in 0 ..< nums1.count { - for j in 0 ..< nums2.count { - let sum1 = nums1[i] + nums2[j] - map[sum1] = (map[sum1] ?? 0) + 1 + // ab和: ab和出现次数 + var countDic = [Int: Int]() + for a in nums1 { + for b in nums2 { + let key = a + b + countDic[key] = countDic[key, default: 0] + 1 } } - // 统计a+b+c+d = 0 出现的次数 - var res = 0 - // 在遍历大num3和num4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。 - for i in 0 ..< nums3.count { - for j in 0 ..< nums4.count { - let sum2 = nums3[i] + nums4[j] - let other = 0 - sum2 - if map.keys.contains(other) { - res += map[other]! - } + + // 通过-(c + d)作为key,去累加ab和出现的次数 + var result = 0 + for c in nums3 { + for d in nums4 { + let key = -(c + d) + result += countDic[key, default: 0] } } - return res + return result } ``` From 1104815b1885d5ce50ff9cd5006a3ee9caaa6a94 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 19 Dec 2021 18:58:57 +0800 Subject: [PATCH 26/35] =?UTF-8?q?=E2=80=9C=E5=80=92=E5=8F=99=E2=80=9D=20->?= =?UTF-8?q?=20=E2=80=9C=E5=80=92=E5=BA=8F=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0031.下一个排列.md | 2 +- problems/0151.翻转字符串里的单词.md | 2 +- problems/0344.反转字符串.md | 1 - problems/0347.前K个高频元素.md | 4 ++-- problems/0416.分割等和子集.md | 2 +- problems/0685.冗余连接II.md | 4 ++-- problems/0746.使用最小花费爬楼梯.md | 2 +- .../1047.删除字符串中的所有相邻重复项.md | 2 +- problems/1049.最后一块石头的重量II.md | 2 +- problems/背包理论基础01背包-2.md | 8 ++++---- 10 files changed, 14 insertions(+), 15 deletions(-) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 10ee0aaa..84bf3e60 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -86,7 +86,7 @@ public: } } } - // 到这里了说明整个数组都是倒叙了,反转一下便可 + // 到这里了说明整个数组都是倒序了,反转一下便可 reverse(nums.begin(), nums.end()); } }; diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 48324cd9..d58ace89 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -40,7 +40,7 @@ 不能使用辅助空间之后,那么只能在原字符串上下功夫了。 -想一下,我们将整个字符串都反转过来,那么单词的顺序指定是倒序了,只不过单词本身也倒叙了,那么再把单词反转一下,单词不就正过来了。 +想一下,我们将整个字符串都反转过来,那么单词的顺序指定是倒序了,只不过单词本身也倒序了,那么再把单词反转一下,单词不就正过来了。 所以解题思路如下: diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 28313839..9176c915 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -101,7 +101,6 @@ s[j] = tmp; s[i] ^= s[j]; s[j] ^= s[i]; s[i] ^= s[j]; - ``` 这道题目还是比较简单的,但是我正好可以通过这道题目说一说在刷题的时候,使用库函数的原则。 diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index e6ad751b..8bd774e9 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -107,7 +107,7 @@ public: } } - // 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒叙来输出到数组 + // 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组 vector result(k); for (int i = k - 1; i >= 0; i--) { result[i] = pri_que.top().first; @@ -180,7 +180,7 @@ class Solution: if len(pri_que) > k: #如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k heapq.heappop(pri_que) - #找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒叙来输出到数组 + #找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组 result = [0] * k for i in range(k-1, -1, -1): result[i] = heapq.heappop(pri_que)[1] diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 23a285f8..45b8b416 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -112,7 +112,7 @@ vector dp(10001, 0); 4. 确定遍历顺序 -在[动态规划:关于01背包问题,你该了解这些!(滚动数组)](https://programmercarl.com/背包理论基础01背包-2.html)中就已经说明:如果使用一维dp数组,物品遍历的for循环放在外层,遍历背包的for循环放在内层,且内层for循环倒叙遍历! +在[动态规划:关于01背包问题,你该了解这些!(滚动数组)](https://programmercarl.com/背包理论基础01背包-2.html)中就已经说明:如果使用一维dp数组,物品遍历的for循环放在外层,遍历背包的for循环放在内层,且内层for循环倒序遍历! 代码如下: diff --git a/problems/0685.冗余连接II.md b/problems/0685.冗余连接II.md index de62432c..d96d4912 100644 --- a/problems/0685.冗余连接II.md +++ b/problems/0685.冗余连接II.md @@ -68,7 +68,7 @@ for (int i = 0; i < n; i++) { ```cpp vector vec; // 记录入度为2的边(如果有的话就两条边) -// 找入度为2的节点所对应的边,注意要倒叙,因为优先返回最后出现在二维数组中的答案 +// 找入度为2的节点所对应的边,注意要倒序,因为优先返回最后出现在二维数组中的答案 for (int i = n - 1; i >= 0; i--) { if (inDegree[edges[i][1]] == 2) { vec.push_back(i); @@ -577,7 +577,7 @@ var findRedundantDirectedConnection = function(edges) { inDegree[edges[i][1]]++; // 统计入度 } let vec = [];// 记录入度为2的边(如果有的话就两条边) - // 找入度为2的节点所对应的边,注意要倒叙,因为优先返回最后出现在二维数组中的答案 + // 找入度为2的节点所对应的边,注意要倒序,因为优先返回最后出现在二维数组中的答案 for (let i = n - 1; i >= 0; i--) { if (inDegree[edges[i][1]] == 2) { vec.push(i); diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index a146cc8b..0009f06c 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -82,7 +82,7 @@ dp[1] = cost[1]; **但是稍稍有点难度的动态规划,其遍历顺序并不容易确定下来**。 -例如:01背包,都知道两个for循环,一个for遍历物品嵌套一个for遍历背包容量,那么为什么不是一个for遍历背包容量嵌套一个for遍历物品呢? 以及在使用一维dp数组的时候遍历背包容量为什么要倒叙呢? +例如:01背包,都知道两个for循环,一个for遍历物品嵌套一个for遍历背包容量,那么为什么不是一个for遍历背包容量嵌套一个for遍历物品呢? 以及在使用一维dp数组的时候遍历背包容量为什么要倒序呢? **这些都是遍历顺序息息相关。当然背包问题后续「代码随想录」都会重点讲解的!** diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 755520f3..d6eefd07 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -63,7 +63,7 @@ ![1047.删除字符串中的所有相邻重复项](https://code-thinking.cdn.bcebos.com/gifs/1047.删除字符串中的所有相邻重复项.gif) -从栈中弹出剩余元素,此时是字符串ac,因为从栈里弹出的元素是倒叙的,所以在对字符串进行反转一下,就得到了最终的结果。 +从栈中弹出剩余元素,此时是字符串ac,因为从栈里弹出的元素是倒序的,所以在对字符串进行反转一下,就得到了最终的结果。 C++代码 : diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 975968de..d64e7e56 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -87,7 +87,7 @@ vector dp(15001, 0); 4. 确定遍历顺序 -在[动态规划:关于01背包问题,你该了解这些!(滚动数组)](https://programmercarl.com/背包理论基础01背包-2.html)中就已经说明:如果使用一维dp数组,物品遍历的for循环放在外层,遍历背包的for循环放在内层,且内层for循环倒叙遍历! +在[动态规划:关于01背包问题,你该了解这些!(滚动数组)](https://programmercarl.com/背包理论基础01背包-2.html)中就已经说明:如果使用一维dp数组,物品遍历的for循环放在外层,遍历背包的for循环放在内层,且内层for循环倒序遍历! 代码如下: diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index 7f646f06..a57bae10 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -103,7 +103,7 @@ for(int i = 0; i < weight.size(); i++) { // 遍历物品 为什么呢? -**倒叙遍历是为了保证物品i只被放入一次!**。但如果一旦正序遍历了,那么物品0就会被重复加入多次! +**倒序遍历是为了保证物品i只被放入一次!**。但如果一旦正序遍历了,那么物品0就会被重复加入多次! 举一个例子:物品0的重量weight[0] = 1,价值value[0] = 15 @@ -115,9 +115,9 @@ dp[2] = dp[2 - weight[0]] + value[0] = 30 此时dp[2]就已经是30了,意味着物品0,被放入了两次,所以不能正序遍历。 -为什么倒叙遍历,就可以保证物品只放入一次呢? +为什么倒序遍历,就可以保证物品只放入一次呢? -倒叙就是先算dp[2] +倒序就是先算dp[2] dp[2] = dp[2 - weight[0]] + value[0] = 15 (dp数组已经都初始化为0) @@ -125,7 +125,7 @@ dp[1] = dp[1 - weight[0]] + value[0] = 15 所以从后往前循环,每次取得状态不会和之前取得状态重合,这样每种物品就只取一次了。 -**那么问题又来了,为什么二维dp数组历的时候不用倒叙呢?** +**那么问题又来了,为什么二维dp数组历的时候不用倒序呢?** 因为对于二维dp,dp[i][j]都是通过上一层即dp[i - 1][j]计算而来,本层的dp[i][j]并不会被覆盖! From cb0f5906fdf7a22a097958cbb89783905baf970f Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 8 Jan 2022 23:55:34 +0800 Subject: [PATCH 27/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0JS=E5=92=8CTS=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/链表理论基础.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index 02b7029e..109aa1ed 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -168,6 +168,32 @@ public class ListNode { } ``` +JavaScript: + +```javascript +class ListNode { + val; + next = null; + constructor(value) { + this.val = value; + this.next = null; + } +} +``` + +TypeScript: + +```typescript +class ListNode { + public val: number; + public next: ListNode = null; + constructor(value: number) { + this.val = value; + this.next = null; + } +} +``` + Python: From 1c595ed05192de37b7c9927b826a365c96ed2fae Mon Sep 17 00:00:00 2001 From: Du Date: Sun, 9 Jan 2022 08:52:20 +0800 Subject: [PATCH 28/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0105.=20=E4=BB=8E?= =?UTF-8?q?=E5=89=8D=E5=BA=8F=E4=B8=8E=E4=B8=AD=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E3=80=81106.=20=E4=BB=8E=E4=B8=AD=E5=BA=8F=E4=B8=8E=E5=90=8E?= =?UTF-8?q?=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=20Swift=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...序与后序遍历序列构造二叉树.md | 102 +++++++++++++++++- 1 file changed, 100 insertions(+), 2 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 487e4f7d..59e0ba53 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -684,7 +684,7 @@ class Solution: root.right = self.buildTree(preorder_right, inorder_right) return root -``` +``` 106.从中序与后序遍历序列构造二叉树 @@ -716,7 +716,7 @@ class Solution: root.right = self.buildTree(inorder_right, postorder_right) return root -``` +``` ## Go @@ -816,6 +816,7 @@ var buildTree = function(preorder, inorder) { ## C 106 从中序与后序遍历序列构造二叉树 + ```c int linearSearch(int* arr, int arrSize, int key) { int i; @@ -847,6 +848,7 @@ struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int po ``` 105 从前序与中序遍历序列构造二叉树 + ```c struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){ // 递归结束条件:传入的数组大小为0 @@ -887,7 +889,103 @@ struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int in // 6.返回根节点 return root; } + ``` +## Swift + +105 从前序与中序遍历序列构造二叉树 + +```swift +class Solution { + func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { + return helper(preorder: preorder, + preorderBegin: 0, + preorderEnd: preorder.count, + inorder: inorder, + inorderBegin: 0, + inorderEnd: inorder.count) + } + + func helper(preorder: [Int], preorderBegin: Int, preorderEnd: Int, inorder: [Int], inorderBegin: Int, inorderEnd: Int) -> TreeNode? { + if preorderBegin == preorderEnd { + return nil + } + + // 前序遍历数组的第一个元素作为分割点 + let rootValue = preorder[preorderBegin] + let root = TreeNode(rootValue) + + + if preorderEnd - preorderBegin == 1 { + return root + } + + var index = 0 // 从中序遍历数组中找到根节点的下标 + if let ind = inorder.firstIndex(of: rootValue) { + index = ind + } + + // 递归 + root.left = helper(preorder: preorder, + preorderBegin: preorderBegin + 1, + preorderEnd: preorderBegin + 1 + index - inorderBegin, + inorder: inorder, + inorderBegin: inorderBegin, + inorderEnd: index) + root.right = helper(preorder: preorder, + preorderBegin: preorderBegin + 1 + index - inorderBegin, + preorderEnd: preorderEnd, + inorder: inorder, + inorderBegin: index + 1, + inorderEnd: inorderEnd) + return root + } +} +``` + +106 从中序与后序遍历序列构造二叉树 + +```swift +class Solution_0106 { + func buildTree(inorder: [Int], inorderBegin: Int, inorderEnd: Int, postorder: [Int], postorderBegin: Int, postorderEnd: Int) -> TreeNode? { + if postorderEnd - postorderBegin < 1 { + return nil + } + + // 后序遍历数组的最后一个元素作为分割点 + let rootValue = postorder[postorderEnd - 1] + let root = TreeNode(rootValue) + + if postorderEnd - postorderBegin == 1 { + return root + } + + // 从中序遍历数组中找到根节点的下标 + var delimiterIndex = 0 + if let index = inorder.firstIndex(of: rootValue) { + delimiterIndex = index + } + + root.left = buildTree(inorder: inorder, + inorderBegin: inorderBegin, + inorderEnd: delimiterIndex, + postorder: postorder, + postorderBegin: postorderBegin, + postorderEnd: postorderBegin + (delimiterIndex - inorderBegin)) + + root.right = buildTree(inorder: inorder, + inorderBegin: delimiterIndex + 1, + inorderEnd: inorderEnd, + postorder: postorder, + postorderBegin: postorderBegin + (delimiterIndex - inorderBegin), + postorderEnd: postorderEnd - 1) + return root + } +} +``` + + + -----------------------
From 1f7f1617296bbb862b5ff6a265659ccd53659af4 Mon Sep 17 00:00:00 2001 From: Du Date: Sun, 9 Jan 2022 08:57:44 +0800 Subject: [PATCH 29/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0105.=20=E4=BB=8E?= =?UTF-8?q?=E5=89=8D=E5=BA=8F=E4=B8=8E=E4=B8=AD=E5=BA=8F=E9=81=8D=E5=8E=86?= =?UTF-8?q?=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E3=80=81106.=20=E4=BB=8E=E4=B8=AD=E5=BA=8F=E4=B8=8E=E5=90=8E?= =?UTF-8?q?=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=20Swift=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0106.从中序与后序遍历序列构造二叉树.md | 1 - 1 file changed, 1 deletion(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 59e0ba53..40d75983 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -889,7 +889,6 @@ struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int in // 6.返回根节点 return root; } - ``` ## Swift From a246b9b4e6dc344925259f64150400ddb7661ed4 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 9 Jan 2022 13:42:10 +0800 Subject: [PATCH 30/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880203.=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=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/0203.移除链表元素.md | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 9d0ef91f..4e7bdd34 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -302,7 +302,63 @@ var removeElements = function(head, val) { }; ``` +TypeScript: + +版本一(在原链表上直接删除): + +```typescript +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ +function removeElements(head: ListNode | null, val: number): ListNode | null { + // 删除头部节点 + while (head !== null && head.val === val) { + head = head.next; + } + if (head === null) return head; + let pre: ListNode = head, cur: ListNode = head.next; + // 删除非头部节点 + while (cur) { + if (cur.val === val) { + pre.next = cur.next; + } else { + pre = pre.next; + } + cur = cur.next; + } + return head; +}; +``` + +版本二(虚拟头节点): + +```typescript +function removeElements(head: ListNode | null, val: number): ListNode | null { + head = new ListNode(0, head); + let pre: ListNode = head, cur: ListNode = head.next; + // 删除非头部节点 + while (cur) { + if (cur.val === val) { + pre.next = cur.next; + } else { + pre = pre.next; + } + cur = cur.next; + } + return head.next; +}; +``` + Swift: + ```swift /** * Definition for singly-linked list. From d2904c2675ecc26f0b385f368c857eeb68d526fa Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 9 Jan 2022 18:19:46 +0800 Subject: [PATCH 31/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880206.=E7=BF=BB?= =?UTF-8?q?=E8=BD=AC=E9=93=BE=E8=A1=A8.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=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/0206.翻转链表.md | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 13ed753c..941928ba 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -314,6 +314,54 @@ var reverseList = function(head) { }; ``` +TypeScript: + +```typescript +// 双指针法 +function reverseList(head: ListNode | null): ListNode | null { + let preNode: ListNode | null = null, + curNode: ListNode | null = head, + tempNode: ListNode | null; + while (curNode) { + tempNode = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + } + return preNode; +}; + +// 递归(从前往后翻转) +function reverseList(head: ListNode | null): ListNode | null { + function recur(preNode: ListNode | null, curNode: ListNode | null): ListNode | null { + if (curNode === null) return preNode; + let tempNode: ListNode | null = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + return recur(preNode, curNode); + } + return recur(null, head); +}; + +// 递归(从后往前翻转) +function reverseList(head: ListNode | null): ListNode | null { + if (head === null) return null; + let newHead: ListNode | null; + function recur(node: ListNode | null, preNode: ListNode | null): void { + if (node.next === null) { + newHead = node; + newHead.next = preNode; + } else { + recur(node.next, node); + node.next = preNode; + } + } + recur(head, null); + return newHead; +}; +``` + Ruby: ```ruby From c5c8fe50b4f101d495e4218722335f467e7e936c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Mon, 10 Jan 2022 15:02:55 +0800 Subject: [PATCH 32/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20101.=20=E5=AF=B9?= =?UTF-8?q?=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 80 ++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index b9dff99c..69bc41d3 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -574,7 +574,87 @@ var isSymmetric = function(root) { }; ``` +## Swift: +> 递归 +```swift +func isSymmetric(_ root: TreeNode?) -> Bool { + return _isSymmetric(root?.left, right: root?.right) +} +func _isSymmetric(_ left: TreeNode?, right: TreeNode?) -> Bool { + // 首先排除空节点情况 + if left == nil && right == nil { + return true + } else if left == nil && right != nil { + return false + } else if left != nil && right == nil { + return false + } else if left!.val != right!.val { + // 进而排除数值不相等的情况 + return false + } + + // left 和 right 都不为空, 且数值也相等就递归 + let inSide = _isSymmetric(left!.right, right: right!.left) + let outSide = _isSymmetric(left!.left, right: right!.right) + return inSide && outSide +} +``` + +> 迭代 - 使用队列 +```swift +func isSymmetric2(_ root: TreeNode?) -> Bool { + guard let root = root else { + return true + } + var queue = [TreeNode?]() + queue.append(root.left) + queue.append(root.right) + while !queue.isEmpty { + let left = queue.removeFirst() + let right = queue.removeFirst() + if left == nil && right == nil { + continue + } + if left == nil || right == nil || left?.val != right?.val { + return false + } + queue.append(left!.left) + queue.append(right!.right) + queue.append(left!.right) + queue.append(right!.left) + } + return true +} +``` + +> 迭代 - 使用栈 +```swift +func isSymmetric3(_ root: TreeNode?) -> Bool { + guard let root = root else { + return true + } + var stack = [TreeNode?]() + stack.append(root.left) + stack.append(root.right) + while !stack.isEmpty { + let left = stack.removeLast() + let right = stack.removeLast() + + if left == nil && right == nil { + continue + } + if left == nil || right == nil || left?.val != right?.val { + return false + } + stack.append(left!.left) + stack.append(right!.right) + stack.append(left!.right) + stack.append(right!.left) + } + return true +} +``` -----------------------
From bc710f263f477d633798c9b357ce7f4178baddbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Tue, 11 Jan 2022 14:45:40 +0800 Subject: [PATCH 33/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20104.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 85b41548..7038598b 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -653,5 +653,82 @@ int maxDepth(struct TreeNode* root){ } ``` +## Swift + +>二叉树最大深度 +```swift +// 递归 - 后序 +func maxDepth1(_ root: TreeNode?) -> Int { + return _maxDepth1(root) +} +func _maxDepth1(_ root: TreeNode?) -> Int { + if root == nil { + return 0 + } + let leftDepth = _maxDepth1(root!.left) + let rightDepth = _maxDepth1(root!.right) + return 1 + max(leftDepth, rightDepth) +} + +// 层序 +func maxDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var queue = [TreeNode]() + queue.append(root) + var res: Int = 0 + while !queue.isEmpty { + res += 1 + for _ in 0 ..< queue.count { + let node = queue.removeFirst() + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return res +} +``` + +>N叉树最大深度 +```swift +// 递归 +func maxDepth(_ root: Node?) -> Int { + guard let root = root else { + return 0 + } + var depth = 0 + for node in root.children { + depth = max(depth, maxDepth(node)) + } + return depth + 1 +} + +// 迭代-层序遍历 +func maxDepth1(_ root: Node?) -> Int { + guard let root = root else { + return 0 + } + var depth = 0 + var queue = [Node]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + depth += 1 + for _ in 0 ..< size { + let node = queue.removeFirst() + for child in node.children { + queue.append(child) + } + } + } + return depth +} +``` + -----------------------
From c93867f0700e455615ca31b564253e1a8f00c603 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Wed, 12 Jan 2022 12:54:12 +0800 Subject: [PATCH 34/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20111.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index fc93d918..a439322a 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -404,8 +404,51 @@ var minDepth = function(root) { }; ``` +## Swift +> 递归 +```Swift +func minDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + if root.left == nil && root.right != nil { + return 1 + minDepth(root.right) + } + if root.left != nil && root.right == nil { + return 1 + minDepth(root.left) + } + return 1 + min(minDepth(root.left), minDepth(root.right)) +} +``` +> 迭代 +```Swift +func minDepth(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var res = 0 + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + res += 1 + for _ in 0 ..< queue.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) + } + } + } + return res +} +``` -----------------------
From c6c39724089a07c5cdd809cca27dd46047fc998f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Thu, 13 Jan 2022 14:08:26 +0800 Subject: [PATCH 35/35] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20222.=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0222.完全二叉树的节点个数.md | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 754a6094..8d38bace 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -522,5 +522,73 @@ int countNodes(struct TreeNode* root){ } ``` +## Swift: + +> 递归 +```swift +func countNodes(_ root: TreeNode?) -> Int { + return _countNodes(root) +} +func _countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + let leftCount = _countNodes(root.left) + let rightCount = _countNodes(root.right) + return 1 + leftCount + rightCount +} +``` + +> 层序遍历 +```Swift +func countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var res = 0 + var queue = [TreeNode]() + queue.append(root) + while !queue.isEmpty { + let size = queue.count + for _ in 0 ..< size { + let node = queue.removeFirst() + res += 1 + if let left = node.left { + queue.append(left) + } + if let right = node.right { + queue.append(right) + } + } + } + return res +} +``` + +> 利用完全二叉树性质 +```Swift +func countNodes(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + var leftNode = root.left + var rightNode = root.right + var leftDepth = 0 + var rightDepth = 0 + while leftNode != nil { + leftNode = leftNode!.left + leftDepth += 1 + } + while rightNode != nil { + rightNode = rightNode!.right + rightDepth += 1 + } + if leftDepth == rightDepth { + return (2 << leftDepth) - 1 + } + return countNodes(root.left) + countNodes(root.right) + 1 +} +``` + -----------------------