diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index fd17af62..a6381eff 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -206,6 +206,48 @@ 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 + } + dict[nums[i]] = i + } + return res +} +``` + +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[] + */ + function twoSum($nums, $target) { + if (count($nums) == 0) { + return []; + } + $table = []; + for ($i = 0; $i < count($nums); $i++) { + $temp = $target - $nums[$i]; + if (isset($table[$temp])) { + return [$table[$temp], $i]; + } + $table[$nums[$i]] = $i; + } + return []; + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 1adb2d24..adb9a113 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -393,6 +393,46 @@ function threeSum(array $nums): array } ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer[][] + */ + function threeSum($nums) { + $res = []; + sort($nums); + for ($i = 0; $i < count($nums); $i++) { + if ($nums[$i] > 0) { + return $res; + } + if ($i > 0 && $nums[$i] == $nums[$i - 1]) { + continue; + } + $left = $i + 1; + $right = count($nums) - 1; + while ($left < $right) { + $sum = $nums[$i] + $nums[$left] + $nums[$right]; + if ($sum < 0) { + $left++; + } + else if ($sum > 0) { + $right--; + } + else { + $res[] = [$nums[$i], $nums[$left], $nums[$right]]; + while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++; + while ($left < $right && $nums[$right] == $nums[$right - 1]) $right--; + $left++; + $right--; + } + } + } + return $res; + } +} +``` ----------------------- diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 1ebf6f49..dfd0e875 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -322,20 +322,20 @@ python3: ```py class Solution: def letterCombinations(self, digits: str) -> List[str]: - self.s = "" res = [] + s = "" letterMap = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"] - if len(digits) == 0: return res - def backtrack(digits,index): + if not len(digits): return res + def backtrack(digits,index, s): if index == len(digits): - return res.append(self.s) + return res.append(s) digit = int(digits[index]) #将index指向的数字转为int letters = letterMap[digit] #取数字对应的字符集 for i in range(len(letters)): - self.s += letters[i] - backtrack(digits,index + 1) #递归,注意index+1,一下层要处理下一个数字 - self.s = self.s[:-1] #回溯 - backtrack(digits,0) + s += letters[i] + backtrack(digits, index+1, s) #递归,注意index+1,一下层要处理下一个数字 + s = s[:-1] #回溯 + backtrack(digits, 0, s) return res ``` diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 6af033b9..c81c5df7 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -310,6 +310,49 @@ var fourSum = function(nums, target) { }; ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[][] + */ + function fourSum($nums, $target) { + $res = []; + sort($nums); + for ($i = 0; $i < count($nums); $i++) { + if ($i > 0 && $nums[$i] == $nums[$i - 1]) { + continue; + } + for ($j = $i + 1; $j < count($nums); $j++) { + if ($j > $i + 1 && $nums[$j] == $nums[$j - 1]) { + continue; + } + $left = $j + 1; + $right = count($nums) - 1; + while ($left < $right) { + $sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right]; + if ($sum < $target) { + $left++; + } + else if ($sum > $target) { + $right--; + } + else { + $res[] = [$nums[$i], $nums[$j], $nums[$left], $nums[$right]]; + while ($left < $right && $nums[$left] == $nums[$left+1]) $left++; + while ($left < $right && $nums[$right] == $nums[$right-1]) $right--; + $left++; + $right--; + } + } + } + } + return $res; + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index e3b75719..78f9afb7 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -246,6 +246,46 @@ func removeElement(_ nums: inout [Int], _ val: Int) -> Int { } ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $val + * @return Integer + */ + function removeElement(&$nums, $val) { + if (count($nums) == 0) { + return 0; + } + // 快慢指针 + $slow = 0; + for ($fast = 0; $fast < count($nums); $fast++) { + if ($nums[$fast] != $val) { + $nums[$slow] = $nums[$fast]; + $slow++; + } + } + return $slow; + } +``` + +C: +```c +int removeElement(int* nums, int numsSize, int val){ + int slow = 0; + for(int fast = 0; fast < numsSize; fast++) { + //若快指针位置的元素不等于要删除的元素 + if(nums[fast] != val) { + //将其挪到慢指针指向的位置,慢指针+1 + nums[slow++] = nums[fast]; + } + } + //最后慢指针的大小就是新的数组的大小 + return slow; +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index df9394eb..001c249e 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -183,6 +183,32 @@ class Solution { } } ``` +```java +// 解法2:通过判断path中是否存在数字,排除已经选择的数字 +class Solution { + List> result = new ArrayList<>(); + LinkedList path = new LinkedList<>(); + public List> permute(int[] nums) { + if (nums.length == 0) return result; + backtrack(nums, path); + return result; + } + public void backtrack(int[] nums, LinkedList path) { + if (path.size() == nums.length) { + result.add(new ArrayList<>(path)); + } + for (int i =0; i < nums.length; i++) { + // 如果path中已有,则跳过 + if (path.contains(nums[i])) { + continue; + } + path.add(nums[i]); + backtrack(nums, path); + path.removeLast(); + } + } +} +``` Python: ```python3 diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index 2322951a..82ca29e6 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -157,6 +157,28 @@ class Solution { } } ``` +```java +// 版本2 +class Solution { + public int[][] merge(int[][] intervals) { + LinkedList res = new LinkedList<>(); + Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[0], o2[0])); + res.add(intervals[0]); + for (int i = 1; i < intervals.length; i++) { + if (intervals[i][0] <= res.getLast()[1]) { + int start = res.getLast()[0]; + int end = Math.max(intervals[i][1], res.getLast()[1]); + res.removeLast(); + res.add(new int[]{start, end}); + } + else { + res.add(intervals[i]); + } + } + return res.toArray(new int[res.size()][]); + } +} +``` Python: ```python diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 4231fb39..3dbc2a50 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -426,6 +426,48 @@ impl Solution { } ``` +PHP: +```php +class Solution { + /** + * @param Integer $n + * @return Integer[][] + */ + function generateMatrix($n) { + // 初始化数组 + $res = array_fill(0, $n, array_fill(0, $n, 0)); + $mid = $loop = floor($n / 2); + $startX = $startY = 0; + $offset = 1; + $count = 1; + while ($loop > 0) { + $i = $startX; + $j = $startY; + for (; $j < $startY + $n - $offset; $j++) { + $res[$i][$j] = $count++; + } + for (; $i < $startX + $n - $offset; $i++) { + $res[$i][$j] = $count++; + } + for (; $j > $startY; $j--) { + $res[$i][$j] = $count++; + } + for (; $i > $startX; $i--) { + $res[$i][$j] = $count++; + } + $startX += 1; + $startY += 1; + $offset += 2; + $loop--; + } + if ($n % 2 == 1) { + $res[$mid][$mid] = $count; + } + return $res; + } +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 01d1a537..9b44b572 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -435,6 +435,59 @@ func backtrack(n,k,start int,track []int){ } ``` +C: +```c +int* path; +int pathTop; +int** ans; +int ansTop; + +void backtracking(int n, int k,int startIndex) { + //当path中元素个数为k个时,我们需要将path数组放入ans二维数组中 + if(pathTop == k) { + //path数组为我们动态申请,若直接将其地址放入二维数组,path数组中的值会随着我们回溯而逐渐变化 + //因此创建新的数组存储path中的值 + int* temp = (int*)malloc(sizeof(int) * k); + int i; + for(i = 0; i < k; i++) { + temp[i] = path[i]; + } + ans[ansTop++] = temp; + return ; + } + + int j; + for(j = startIndex; j <=n ;j++) { + //将当前结点放入path数组 + path[pathTop++] = j; + //进行递归 + backtracking(n, k, j + 1); + //进行回溯,将数组最上层结点弹出 + pathTop--; + } +} + +int** combine(int n, int k, int* returnSize, int** returnColumnSizes){ + //path数组存储符合条件的结果 + path = (int*)malloc(sizeof(int) * k); + //ans二维数组存储符合条件的结果数组的集合。(数组足够大,避免极端情况) + ans = (int**)malloc(sizeof(int*) * 10000); + pathTop = ansTop = 0; + + //回溯算法 + backtracking(n, k, 1); + //最后的返回大小为ans数组大小 + *returnSize = ansTop; + //returnColumnSizes数组存储ans二维数组对应下标中一维数组的长度(都为k) + *returnColumnSizes = (int*)malloc(sizeof(int) *(*returnSize)); + int i; + for(i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = k; + } + //返回ans二维数组 + return ans; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 171023dd..136ceb34 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -242,8 +242,59 @@ var combine = function(n, k) { }; ``` +C: +```c +int* path; +int pathTop; +int** ans; +int ansTop; +void backtracking(int n, int k,int startIndex) { + //当path中元素个数为k个时,我们需要将path数组放入ans二维数组中 + if(pathTop == k) { + //path数组为我们动态申请,若直接将其地址放入二维数组,path数组中的值会随着我们回溯而逐渐变化 + //因此创建新的数组存储path中的值 + int* temp = (int*)malloc(sizeof(int) * k); + int i; + for(i = 0; i < k; i++) { + temp[i] = path[i]; + } + ans[ansTop++] = temp; + return ; + } + int j; + for(j = startIndex; j <= n- (k - pathTop) + 1;j++) { + //将当前结点放入path数组 + path[pathTop++] = j; + //进行递归 + backtracking(n, k, j + 1); + //进行回溯,将数组最上层结点弹出 + pathTop--; + } +} + +int** combine(int n, int k, int* returnSize, int** returnColumnSizes){ + //path数组存储符合条件的结果 + path = (int*)malloc(sizeof(int) * k); + //ans二维数组存储符合条件的结果数组的集合。(数组足够大,避免极端情况) + ans = (int**)malloc(sizeof(int*) * 10000); + pathTop = ansTop = 0; + + //回溯算法 + backtracking(n, k, 1); + //最后的返回大小为ans数组大小 + *returnSize = ansTop; + //returnColumnSizes数组存储ans二维数组对应下标中一维数组的长度(都为k) + *returnColumnSizes = (int*)malloc(sizeof(int) *(*returnSize)); + int i; + for(i = 0; i < *returnSize; i++) { + (*returnColumnSizes)[i] = k; + } + //返回ans二维数组 + return ans; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index a57a92aa..ac43f0a5 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -87,28 +87,48 @@ public: python代码: + +```python3 + +class Solution: + """二叉树层序遍历迭代解法""" + + def levelOrder(self, root: TreeNode) -> List[List[int]]: + results = [] + if not root: + return results + + from collections import deque + que = deque([root]) + + while que: + size = len(que) + result = [] + for _ in range(size): + cur = que.popleft() + result.append(cur.val) + if cur.left: + que.append(cur.left) + if cur.right: + que.append(cur.right) + results.append(result) + + return results +``` ```python +# 递归法 class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: - if not root: - return [] - - queue = [root] - out_list = [] - - while queue: - length = len(queue) - in_list = [] - for _ in range(length): - curnode = queue.pop(0) # (默认移除列表最后一个元素)这里需要移除队列最头上的那个 - in_list.append(curnode.val) - if curnode.left: queue.append(curnode.left) - if curnode.right: queue.append(curnode.right) - out_list.append(in_list) - - return out_list + res = [] + def helper(root, depth): + if not root: return [] + if len(res) == depth: res.append([]) # start the current depth + res[depth].append(root.val) # fulfil the current depth + if root.left: helper(root.left, depth + 1) # process child nodes for the next depth + if root.right: helper(root.right, depth + 1) + helper(root, 0) + return res ``` - java: ```Java @@ -274,29 +294,29 @@ python代码: ```python class Solution: + """二叉树层序遍历II迭代解法""" + def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: + results = [] if not root: - return [] - quene = [root] - out_list = [] + return results - while quene: - in_list = [] - for _ in range(len(quene)): - node = quene.pop(0) - in_list.append(node.val) - if node.left: - quene.append(node.left) - if node.right: - quene.append(node.right) - - out_list.append(in_list) - - out_list.reverse() - return out_list - -# 执行用时:36 ms, 在所有 Python3 提交中击败了92.00%的用户 -# 内存消耗:15.2 MB, 在所有 Python3 提交中击败了63.76%的用户 + from collections import deque + que = deque([root]) + + while que: + result = [] + for _ in range(len(que)): + cur = que.popleft() + result.append(cur.val) + if cur.left: + que.append(cur.left) + if cur.right: + que.append(cur.right) + results.append(result) + + results.reverse() + return results ``` Java: @@ -628,32 +648,29 @@ python代码: ```python class Solution: + """二叉树层平均值迭代解法""" + def averageOfLevels(self, root: TreeNode) -> List[float]: + results = [] if not root: - return [] + return results - quene = deque([root]) - out_list = [] - - while quene: - in_list = [] - - for _ in range(len(quene)): - node = quene.popleft() - in_list.append(node.val) - if node.left: - quene.append(node.left) - if node.right: - quene.append(node.right) - - out_list.append(in_list) - - out_list = map(lambda x: sum(x) / len(x), out_list) - - return out_list + from collections import deque + que = deque([root]) -# 执行用时:56 ms, 在所有 Python3 提交中击败了81.48%的用户 -# 内存消耗:17 MB, 在所有 Python3 提交中击败了89.68%的用户 + while que: + size = len(que) + sum_ = 0 + for _ in range(size): + cur = que.popleft() + sum_ += cur.val + if cur.left: + que.append(cur.left) + if cur.right: + que.append(cur.right) + results.append(sum_ / size) + + return results ``` java: @@ -823,52 +840,28 @@ public: python代码: ```python - class Solution: + """N叉树的层序遍历迭代法""" + def levelOrder(self, root: 'Node') -> List[List[int]]: + results = [] if not root: - return [] + return results - quene = deque([root]) - out_list = [] - - while quene: - in_list = [] - - for _ in range(len(quene)): - node = quene.popleft() - in_list.append(node.val) - if node.children: - # 这个地方要用extend而不是append,我们看下面的例子: - # In [18]: alist=[] - # In [19]: alist.append([1,2,3]) - # In [20]: alist - # Out[20]: [[1, 2, 3]] - # In [21]: alist.extend([4,5,6]) - # In [22]: alist - # Out[22]: [[1, 2, 3], 4, 5, 6] - # 可以看到extend对要添加的list进行了一个解包操作 - # print(root.children),可以得到children是一个包含 - # 孩子节点地址的list,我们使用for遍历quene的时候, - # 希望quene是一个单层list,所以要用extend - # 使用extend的情况,如果print(quene),结果是 - # deque([<__main__.Node object at 0x7f60763ae0a0>]) - # deque([<__main__.Node object at 0x7f607636e6d0>, <__main__.Node object at 0x7f607636e130>, <__main__.Node object at 0x7f607636e310>]) - # deque([<__main__.Node object at 0x7f607636e880>, <__main__.Node object at 0x7f607636ef10>]) - # 可以看到是单层list - # 如果使用append,print(quene)的结果是 - # deque([<__main__.Node object at 0x7f18907530a0>]) - # deque([[<__main__.Node object at 0x7f18907136d0>, <__main__.Node object at 0x7f1890713130>, <__main__.Node object at 0x7f1890713310>]]) - # 可以看到是两层list,这样for的遍历就会报错 - - quene.extend(node.children) - - out_list.append(in_list) + from collections import deque + que = deque([root]) - return out_list - -# 执行用时:60 ms, 在所有 Python3 提交中击败了76.99%的用户 -# 内存消耗:16.5 MB, 在所有 Python3 提交中击败了89.19%的用户 + while que: + result = [] + for _ in range(len(que)): + cur = que.popleft() + result.append(cur.val) + # cur.children 是 Node 对象组成的列表,也可能为 None + if cur.children: + que.extend(cur.children) + results.append(result) + + return results ``` java: diff --git a/problems/0115.不同的子序列.md b/problems/0115.不同的子序列.md index a5162ae0..908682dd 100644 --- a/problems/0115.不同的子序列.md +++ b/problems/0115.不同的子序列.md @@ -221,6 +221,30 @@ class SolutionDP2: ``` Go: +```go +func numDistinct(s string, t string) int { + dp:= make([][]int,len(s)+1) + for i:=0;i= 0) + return 0; + //若累加最小值为负,则找到一个非零元素(加油量大于出油量)出发。返回坐标 + for(i = gasSize - 1; i >= 0; i--) { + min+=(gas[i]-cost[i]); + if(min >= 0) + return i; + } + //逻辑上不会返回这个0 + return 0; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 84e348a9..c4a9c7e0 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -467,6 +467,85 @@ function reverse(strArr, start, end) { } ``` +Swift: + +```swift +func reverseWords(_ s: String) -> String { + var stringArr = removeSpace(s) + reverseString(&stringArr, startIndex: 0, endIndex: stringArr.count - 1) + reverseWord(&stringArr) + return String(stringArr) +} + +/// 1、移除多余的空格(前后所有的空格,中间只留一个空格) +func removeSpace(_ s: String) -> [Character] { + let ch = Array(s) + var left = 0 + var right = ch.count - 1 + // 忽略字符串前面的所有空格 + while ch[left] == " " { + left += 1 + } + // 忽略字符串后面的所有空格 + while ch[right] == " " { + right -= 1 + } + + // 接下来就是要处理中间的多余空格 + var lastArr = Array() + while left <= right { + // 准备加到新字符串当中的字符 + let char = ch[left] + // 新的字符串的最后一个字符;或者原字符串中,准备加到新字符串的那个字符;这两个字符当中,只要有一个不是空格,就可以加到新的字符串当中 + if char != " " || lastArr[lastArr.count - 1] != " " { + lastArr.append(char) + } + + left += 1 + } + return lastArr +} + +/// 2、反转整个字符串 +func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) { + var start = startIndex + var end = endIndex + while start < end { + (s[start], s[end]) = (s[end], s[start]) + start += 1 + end -= 1 + } +} + +/// 3、再次将字符串里面的单词反转 +func reverseWord(_ s: inout [Character]) { + var start = 0 + var end = 0 + var entry = false + + for i in 0.. Int { + var sum = 0 + var num = number + while num > 0 { + let temp = num % 10 + sum += (temp * temp) + num /= 10 + } + return sum +} +func isHappy(_ n: Int) -> Bool { + var set = Set() + var num = n + while true { + let sum = self.getSum(num) + if sum == 1 { + return true + } + // 如果这个sum曾经出现过,说明已经陷入了无限循环了 + if set.contains(sum) { + return false + } else { + set.insert(sum) + } + num = sum + } +} +``` +PHP: +```php +class Solution { + /** + * @param Integer $n + * @return Boolean + */ + function isHappy($n) { + // use a set to record sum + // whenever there is a duplicated, stop + // == 1 return true, else false + $table = []; + while ($n != 1 && !isset($table[$n])) { + $table[$n] = 1; + $n = self::getNextN($n); + } + return $n == 1; + } + + function getNextN(int $n) { + $res = 0; + while ($n > 0) { + $temp = $n % 10; + $res += $temp * $temp; + $n = floor($n / 10); + } + return $res; + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 555dad03..c4f187e8 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -331,8 +331,32 @@ func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { } ``` - - +PHP: +```php +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + // 虚拟头+双指针 +func removeElements(head *ListNode, val int) *ListNode { + dummyHead := &ListNode{} + dummyHead.Next = head + pred := dummyHead + cur := head + for cur != nil { + if cur.Val == val { + pred.Next = cur.Next + } else { + pred = cur + } + cur = cur.Next + } + return dummyHead.Next +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index ceca8c87..7c3fd0e7 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -264,6 +264,34 @@ impl Solution { } ``` +PHP: +```php +// 双指针 - 滑动窗口 +class Solution { + /** + * @param Integer $target + * @param Integer[] $nums + * @return Integer + */ + function minSubArrayLen($target, $nums) { + if (count($nums) < 1) { + return 0; + } + $sum = 0; + $res = PHP_INT_MAX; + $left = 0; + for ($right = 0; $right < count($nums); $right++) { + $sum += $nums[$right]; + while ($sum >= $target) { + $res = min($res, $right - $left + 1); + $sum -= $nums[$left]; + $left++; + } + } + return $res == PHP_INT_MAX ? 0 : $res; + } +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 6268c447..13017f7f 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -204,7 +204,27 @@ class Solution { } } ``` - +```java +class Solution { + // 迭代法 + public int countNodes(TreeNode root) { + if (root == null) return 0; + Queue queue = new LinkedList<>(); + queue.offer(root); + int result = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + while (size -- > 0) { + TreeNode cur = queue.poll(); + result++; + if (cur.left != null) queue.offer(cur.left); + if (cur.right != null) queue.offer(cur.right); + } + } + return result; + } +} +``` ```java class Solution { /** diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index afa563e3..8d4db953 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -359,6 +359,71 @@ class MyStack: Go: +```go +type MyStack struct { + queue []int//创建一个队列 +} + + +/** Initialize your data structure here. */ +func Constructor() MyStack { + return MyStack{ //初始化 + queue:make([]int,0), + } +} + + +/** Push element x onto stack. */ +func (this *MyStack) Push(x int) { + //添加元素 + this.queue=append(this.queue,x) +} + + +/** Removes the element on top of the stack and returns that element. */ +func (this *MyStack) Pop() int { + n:=len(this.queue)-1//判断长度 + for n!=0{ //除了最后一个,其余的都重新添加到队列里 + val:=this.queue[0] + this.queue=this.queue[1:] + this.queue=append(this.queue,val) + n-- + } + //弹出元素 + val:=this.queue[0] + this.queue=this.queue[1:] + return val + +} + + +/** Get the top element. */ +func (this *MyStack) Top() int { + //利用Pop函数,弹出来的元素重新添加 + val:=this.Pop() + this.queue=append(this.queue,val) + return val +} + + +/** Returns whether the stack is empty. */ +func (this *MyStack) Empty() bool { + return len(this.queue)==0 +} + + +/** + * Your MyStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * param_2 := obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.Empty(); + */ +``` + + + javaScript: 使用数组(push, shift)模拟队列 diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index a4a73603..9f6bb90f 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -205,33 +205,26 @@ class MyQueue: def pop(self) -> int: """ - 1. 检查如果out里面元素,则直接pop - 2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面 - 3. 直接把in剩下的元素pop出来,就是queue头部的 + Removes the element from in front of queue and returns that element. """ - if self.empty: + if self.empty(): return None if self.stack_out: return self.stack_out.pop() else: - for i in range(1, len(self.stack_in)): + for i in range(len(self.stack_in)): self.stack_out.append(self.stack_in.pop()) - return self.stack_in.pop() + return self.stack_out.pop() def peek(self) -> int: """ - 1. 查out有没有元素,有就把最上面的返回 - 2. 如果out没有元素,就把in最下面的返回 + Get the front element. """ - if self.empty: - return None - - if self.stack_out: - return self.stack_out[-1] - else: - return self.stack_in[0] + ans = self.pop() + self.stack_out.append(ans) + return ans def empty(self) -> bool: diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index 04015a7f..631d2f6b 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -144,6 +144,75 @@ public: ## Java ```java +// 方法一,使用数组 +class Solution { + public boolean isPalindrome(ListNode head) { + int len = 0; + // 统计链表长度 + ListNode cur = head; + while (cur != null) { + len++; + cur = cur.next; + } + cur = head; + int[] res = new int[len]; + // 将元素加到数组之中 + for (int i = 0; i < res.length; i++){ + res[i] = cur.val; + cur = cur.next; + } + // 比较回文 + for (int i = 0, j = len - 1; i < j; i++, j--){ + if (res[i] != res[j]){ + return false; + } + } + return true; + } +} + +// 方法二,快慢指针 +class Solution { + public boolean isPalindrome(ListNode head) { + // 如果为空或者仅有一个节点,返回true + if (head == null && head.next == null) return true; + ListNode slow = head; + ListNode fast = head; + ListNode pre = head; + while (fast != null && fast.next != null){ + pre = slow; // 记录slow的前一个结点 + slow = slow.next; + fast = fast.next.next; + } + pre.next = null; // 分割两个链表 + + // 前半部分 + ListNode cur1 = head; + // 后半部分。这里使用了反转链表 + ListNode cur2 = reverseList(slow); + + while (cur1 != null){ + if (cur1.val != cur2.val) return false; + + // 注意要移动两个结点 + cur1 = cur1.next; + cur2 = cur2.next; + } + return true; + } + ListNode reverseList(ListNode head){ + // 反转链表 + ListNode tmp = null; + ListNode pre = null; + while (head != null){ + tmp = head.next; + head.next = pre; + pre = head; + head = tmp; + } + return pre; + } +} ``` ## Python @@ -209,11 +278,13 @@ class Solution: ## Go ```go + ``` ## JavaScript ```js + ``` diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1b6b3109..3416ac06 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -221,6 +221,41 @@ func isAnagram(_ s: String, _ t: String) -> Bool { } ``` +PHP: +```php +class Solution { + /** + * @param String $s + * @param String $t + * @return Boolean + */ + function isAnagram($s, $t) { + if (strlen($s) != strlen($t)) { + return false; + } + $table = []; + for ($i = 0; $i < strlen($s); $i++) { + if (!isset($table[$s[$i]])) { + $table[$s[$i]] = 1; + } else { + $table[$s[$i]]++; + } + if (!isset($table[$t[$i]])) { + $table[$t[$i]] = -1; + } else { + $table[$t[$i]]--; + } + } + foreach ($table as $record) { + if ($record != 0) { + return false; + } + } + return true; + } +} +``` + ## 相关题目 * 383.赎金信 diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 54be5cc4..6012e118 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -189,6 +189,79 @@ class Solution: Go: +```go +//方法一:小顶堆 +func topKFrequent(nums []int, k int) []int { + map_num:=map[int]int{} + //记录每个元素出现的次数 + for _,item:=range nums{ + map_num[item]++ + } + h:=&IHeap{} + heap.Init(h) + //所有元素入堆,堆的长度为k + for key,value:=range map_num{ + heap.Push(h,[2]int{key,value}) + if h.Len()>k{ + heap.Pop(h) + } + } + res:=make([]int,k) + //按顺序返回堆中的元素 + for i:=0;imap_num[ans[b]] + }) + return ans[:k] +} +``` + + + javaScript: ```js diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 752eee51..0cbdf85f 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -209,6 +209,35 @@ func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { } ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersection($nums1, $nums2) { + if (count($nums1) == 0 || count($nums2) == 0) { + return []; + } + $counts = []; + $res = []; + foreach ($nums1 as $num) { + $counts[$num] = 1; + } + foreach ($nums2 as $num) { + if (isset($counts[$num])) { + $res[] = $num; + } + unset($counts[$num]); + } + + return $res; + } +} +``` + ## 相关题目 * 350.两个数组的交集 II diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 64503cef..d1594015 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -267,6 +267,54 @@ var canConstruct = function(ransomNote, magazine) { ``` +PHP: +```php +class Solution { + /** + * @param String $ransomNote + * @param String $magazine + * @return Boolean + */ + function canConstruct($ransomNote, $magazine) { + if (count($ransomNote) > count($magazine)) { + return false; + } + $map = []; + for ($i = 0; $i < strlen($magazine); $i++) { + $map[$magazine[$i]] = ($map[$magazine[$i]] ?? 0) + 1; + } + for ($i = 0; $i < strlen($ransomNote); $i++) { + if (!isset($map[$ransomNote[$i]]) || --$map[$ransomNote[$i]] < 0) { + return false; + } + } + return true; + } +``` + +Swift: +```swift +func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool { + var record = Array(repeating: 0, count: 26); + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + for unicodeScalar in magazine.unicodeScalars { + // 通过record 记录 magazine 里各个字符出现的次数 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] += 1 + } + for unicodeScalar in ransomNote.unicodeScalars { + // 遍历 ransomNote,在record里对应的字符个数做 -- 操作 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] -= 1 + // 如果小于零说明在magazine没有 + if record[idx] < 0 { + return false + } + } + return true +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0392.判断子序列.md b/problems/0392.判断子序列.md index 54c16489..784e3bbc 100644 --- a/problems/0392.判断子序列.md +++ b/problems/0392.判断子序列.md @@ -203,6 +203,25 @@ const isSubsequence = (s, t) => { }; ``` +Go: +```go +func isSubsequence(s string, t string) bool { + dp := make([][]int,len(s)+1) + for i:=0;i queue = new LinkedList<>(); + queue.offer(root); + while (!queue.isEmpty()) { + int size = queue.size(); + while (size -- > 0) { + TreeNode node = queue.poll(); + if (node.left != null) { // 左节点不为空 + queue.offer(node.left); + if (node.left.left == null && node.left.right == null){ // 左叶子节点 + sum += node.left.val; + } + } + if (node.right != null) queue.offer(node.right); + } + } + return sum; + } +} +``` ## Python diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index 7b8130f0..07141558 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -218,6 +218,30 @@ var findMinArrowShots = function(points) { }; ``` +C: +```c +int cmp(const void *a,const void *b) +{ + return ((*((int**)a))[0] > (*((int**)b))[0]); +} + +int findMinArrowShots(int** points, int pointsSize, int* pointsColSize){ + //将points数组作升序排序 + qsort(points, pointsSize, sizeof(points[0]),cmp); + + int arrowNum = 1; + int i = 1; + for(i = 1; i < pointsSize; i++) { + //若前一个气球与当前气球不重叠,证明需要增加箭的数量 + if(points[i][0] > points[i-1][1]) + arrowNum++; + else + //若前一个气球与当前气球重叠,判断并更新最小的x_end + points[i][1] = points[i][1] > points[i-1][1] ? points[i-1][1] : points[i][1]; + } + return arrowNum; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 4e61dc2f..a82c617b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -221,6 +221,66 @@ var fourSumCount = function(nums1, nums2, nums3, nums4) { ``` +PHP: +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @param Integer[] $nums3 + * @param Integer[] $nums4 + * @return Integer + */ + function fourSumCount($nums1, $nums2, $nums3, $nums4) { + $map = []; + foreach ($nums1 as $n1) { + foreach ($nums2 as $n2) { + $temp = $n1 + $n2; + $map[$temp] = isset($map[$temp]) ? $map[$temp]+1 : 1; + } + } + $count = 0; + foreach ($nums3 as $n3) { + foreach ($nums4 as $n4) { + $temp = 0 - $n3 - $n4; + if (isset($map[$temp])) { + $count += $map[$temp]; + } + } + } + return $count; + } +} +``` + + +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 + } + } + // 统计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]! + } + } + } + return res +} +``` ----------------------- diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 1e1c4afe..8e20c402 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -197,11 +197,10 @@ func findContentChildren(g []int, s []int) int { return child } - +``` Javascript: -​```Javascript - +``` var findContentChildren = function(g, s) { g = g.sort((a, b) => a - b) s = s.sort((a, b) => a - b) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 46f6b796..ae6719ec 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -265,7 +265,7 @@ func getMinimumDifference(root *TreeNode) int { ``` ## JavaScript - +递归 先转换为有序数组 ```javascript /** * Definition for a binary tree node. @@ -297,6 +297,47 @@ var getMinimumDifference = function (root) { return diff; }; ``` +递归 在递归的过程中更新最小值 +```js +var getMinimumDifference = function(root) { + let res = Infinity + let preNode = null + // 中序遍历 + const inorder = (node) => { + if(!node) return + inorder(node.left) + // 更新res + if(preNode) res = Math.min(res, node.val - preNode.val) + // 记录前一个节点 + preNode = node + inorder(node.right) + } + inorder(root) + return res +} +``` + +迭代 中序遍历 +```js +var getMinimumDifference = function(root) { + let stack = [] + let cur = root + let res = Infinity + let pre = null + while(cur || stack.length) { + if(cur) { + stack.push(cur) + cur = cur.left + } else { + cur = stack.pop() + if(pre) res = Math.min(res, cur.val - pre.val) + pre = cur + cur = cur.right + } + } + return res +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index 89a8f57c..91b07ca9 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -147,8 +147,38 @@ class Solution: ``` Go: +```go +func minDistance(word1 string, word2 string) int { + dp := make([][]int, len(word1)+1) + for i := 0; i < len(dp); i++ { + dp[i] = make([]int, len(word2)+1) + } + //初始化 + for i := 0; i < len(dp); i++ { + dp[i][0] = i + } + for j := 0; j < len(dp[0]); j++ { + dp[0][j] = j + } + for i := 1; i < len(dp); i++ { + for j := 1; j < len(dp[i]); j++ { + if word1[i-1] == word2[j-1] { + dp[i][j] = dp[i-1][j-1] + } else { + dp[i][j] = min(min(dp[i-1][j]+1, dp[i][j-1]+1), dp[i-1][j-1]+2) + } + } + } + return dp[len(dp)-1][len(dp[0])-1] +} - +func min(a, b int) int { + if a < b { + return a + } + return b +} +``` Javascript: ```javascript const minDistance = (word1, word2) => { diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 495f7367..f358d2be 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -478,6 +478,38 @@ int search(int* nums, int numsSize, int target){ } ``` +**PHP:** +```php +// 左闭右闭区间 +class Solution { + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer + */ + function search($nums, $target) { + if (count($nums) == 0) { + return -1; + } + $left = 0; + $right = count($nums) - 1; + while ($left <= $right) { + $mid = floor(($left + $right) / 2); + if ($nums[$mid] == $target) { + return $mid; + } + if ($nums[$mid] > $target) { + $right = $mid - 1; + } + else { + $left = $mid + 1; + } + } + return -1; + } +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 50db8868..7c54a2fe 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -152,6 +152,25 @@ class Solution: ``` Go: +```Go +func maxProfit(prices []int, fee int) int { + n := len(prices) + dp := make([][2]int, n) + dp[0][0] = -prices[0] + for i := 1; i < n; i++ { + dp[i][1] = max(dp[i-1][1], dp[i-1][0]+prices[i]-fee) + dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i]) + } + return dp[n-1][1] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` Javascript: ```javascript diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 737e92a0..a5fa71a7 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -368,7 +368,34 @@ class Solution: return result ``` Go: +```go +const inf = math.MaxInt64 / 2 +func minCameraCover(root *TreeNode) int { + var dfs func(*TreeNode) (a, b, c int) + dfs = func(node *TreeNode) (a, b, c int) { + if node == nil { + return inf, 0, 0 + } + lefta, leftb, leftc := dfs(node.Left) + righta, rightb, rightc := dfs(node.Right) + a = leftc + rightc + 1 + b = min(a, min(lefta+rightb, righta+leftb)) + c = min(a, leftb+rightb) + return + } + _, ans, _ := dfs(root) + return ans +} + +func min(a, b int) int { + if a <= b { + return a + } + return b +} + +``` Javascript: ```Javascript var minCameraCover = function(root) { diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 13142853..a57af3c1 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -271,6 +271,69 @@ end ``` +C: +```c +int* sortedSquares(int* nums, int numsSize, int* returnSize){ + //返回的数组大小就是原数组大小 + *returnSize = numsSize; + //创建两个指针,right指向数组最后一位元素,left指向数组第一位元素 + int right = numsSize - 1; + int left = 0; + + //最后要返回的结果数组 + int* ans = (int*)malloc(sizeof(int) * numsSize); + int index; + for(index = numsSize - 1; index >= 0; index--) { + //左指针指向元素的平方 + int lSquare = nums[left] * nums[left]; + //右指针指向元素的平方 + int rSquare = nums[right] * nums[right]; + //若左指针指向元素平方比右指针指向元素平方大,将左指针指向元素平方放入结果数组。左指针右移一位 + if(lSquare > rSquare) { + ans[index] = lSquare; + left++; + } + //若右指针指向元素平方比左指针指向元素平方大,将右指针指向元素平方放入结果数组。右指针左移一位 + else { + ans[index] = rSquare; + right--; + } + } + //返回结果数组 + return ans; +} +``` + +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer[] + */ + function sortedSquares($nums) { + // 双指针法 + $res = []; + for ($i = 0; $i < count($nums); $i++) { + $res[$i] = 0; + } + $k = count($nums) - 1; + for ($i = 0, $j = count($nums) - 1; $i <= $j; ) { + if ($nums[$i] ** 2 < $nums[$j] ** 2) { + $res[$k--] = $nums[$j] ** 2; + $j--; + } + else { + $res[$k--] = $nums[$i] ** 2; + $i++; + } + } + return $res; + } +} +``` + + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index f7d323aa..c0ca578e 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -268,6 +268,47 @@ func min(a,b int)int{ return a } ``` + +Swift: +```swift +func commonChars(_ words: [String]) -> [String] { + var res = [String]() + if words.count < 1 { + return res + } + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + let lettersMaxCount = 26 + // 用于统计所有字符串每个字母出现的 最小 频率 + var hash = Array(repeating: 0, count: lettersMaxCount) + // 统计第一个字符串每个字母出现的次数 + for unicodeScalar in words.first!.unicodeScalars { + hash[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 统计除第一个字符串每个字母出现的次数 + for idx in 1 ..< words.count { + var hashOtherStr = Array(repeating: 0, count: lettersMaxCount) + for unicodeScalar in words[idx].unicodeScalars { + hashOtherStr[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1 + } + // 更新hash,保证hash里统计的字母为出现的最小频率 + for k in 0 ..< lettersMaxCount { + hash[k] = min(hash[k], hashOtherStr[k]) + } + } + // 将hash统计的字符次数,转成输出形式 + for i in 0 ..< lettersMaxCount { + while hash[i] != 0 { // 注意这里是while,多个重复的字符 + let currentUnicodeScalarValue: UInt32 = UInt32(i) + aUnicodeScalarValue + let currentUnicodeScalar: UnicodeScalar = UnicodeScalar(currentUnicodeScalarValue)! + let outputStr = String(currentUnicodeScalar) // UnicodeScalar -> String + res.append(outputStr) + hash[i] -= 1 + } + } + return res +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 30718b13..020476a9 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -110,15 +110,16 @@ class Solution { int len = nums.length; for (int i = 0; i < len; i++) { //从前向后遍历,遇到负数将其变为正数,同时K-- - if (nums[i] < 0 && k > 0) { + if (nums[i] < 0 && K > 0) { nums[i] = -nums[i]; - k--; + K--; } } // 如果K还大于0,那么反复转变数值最小的元素,将K用完 - if (k % 2 == 1) nums[len - 1] = -nums[len - 1]; - + + if (K % 2 == 1) nums[len - 1] = -nums[len - 1]; return Arrays.stream(nums).sum(); + } } ``` diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index a1d65070..84363610 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -27,7 +27,7 @@ 我们先看一下前序遍历。 -前序遍历是中左右,每次先处理的是中间节点,那么先将跟节点放入栈中,然后将右孩子加入栈,再加入左孩子。 +前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。 为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。 @@ -140,7 +140,7 @@ public: # 总结 -此时我们用迭代法写出了二叉树的前后中序遍历,大家可以看出前序和中序是完全两种代码风格,并不想递归写法那样代码稍做调整,就可以实现前后中序。 +此时我们用迭代法写出了二叉树的前后中序遍历,大家可以看出前序和中序是完全两种代码风格,并不像递归写法那样代码稍做调整,就可以实现前后中序。 **这是因为前序遍历中访问节点(遍历节点)和处理节点(将元素放进result数组中)可以同步处理,但是中序就无法做到同步!** diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index f4d3368c..d8aaca67 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -214,6 +214,34 @@ var reverseLeftWords = function (s, n) { }; ``` +Swift: + +```swift +func reverseLeftWords(_ s: String, _ n: Int) -> String { + var ch = Array(s) + let len = ch.count + // 反转区间[0, n - 1] + reverseString(&ch, startIndex: 0, endIndex: n - 1) + // 反转区间[n, len - 1] + reverseString(&ch, startIndex: n, endIndex: len - 1) + // 反转区间[0, len - 1],也就是整个字符串反转 + reverseString(&ch, startIndex: 0, endIndex: len - 1) + return String(ch) +} + +func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) { + var start = startIndex + var end = endIndex + while start < end { + (s[start], s[end]) = (s[end], s[start]) + start += 1 + end -= 1 + } +} +``` + + +