From 97cd84d47870a8ab2aad30838b9ebc1a9a450099 Mon Sep 17 00:00:00 2001 From: zcxzcxzcx <18810692826@163.com> Date: Sun, 2 Jan 2022 22:16:26 +0800 Subject: [PATCH 001/257] =?UTF-8?q?Create=200093.=E5=A4=8D=E5=8E=9FIP?= =?UTF-8?q?=E5=9C=B0=E5=9D=80.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化时间复杂度,更好地剪枝(java版本) --- problems/0093.复原IP地址.md | 42 +++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 3e7cd1ad..67bb1bbe 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -304,6 +304,48 @@ class Solution { return true; } } + +//方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度 +class Solution { + List result = new ArrayList(); + StringBuilder stringBuilder = new StringBuilder(); + + public List restoreIpAddresses(String s) { + restoreIpAddressesHandler(s, 0, 0); + return result; + } + + // number表示stringbuilder中ip段的数量 + public void restoreIpAddressesHandler(String s, int start, int number) { + // 如果start等于s的长度并且ip段的数量是4,则加入结果集,并返回 + if (start == s.length() && number == 4) { + result.add(stringBuilder.toString()); + return; + } + // 如果start等于s的长度但是ip段的数量不为4,或者ip段的数量为4但是start小于s的长度,则直接返回 + if (start == s.length() || number == 4) { + return; + } + // 剪枝:ip段的长度最大是3,并且ip段处于[0,255] + for (int i = start; i < s.length() && i - start < 3 && Integer.parseInt(s.substring(start, i + 1)) >= 0 + && Integer.parseInt(s.substring(start, i + 1)) <= 255; i++) { + // 如果ip段的长度大于1,并且第一位为0的话,continue + if (i + 1 - start > 1 && s.charAt(start) - '0' == 0) { + continue; + } + stringBuilder.append(s.substring(start, i + 1)); + // 当stringBuilder里的网段数量小于3时,才会加点;如果等于3,说明已经有3段了,最后一段不需要再加点 + if (number < 3) { + stringBuilder.append("."); + } + number++; + restoreIpAddressesHandler(s, i + 1, number); + number--; + // 删除当前stringBuilder最后一个网段,注意考虑点的数量的问题 + stringBuilder.delete(start + number, i + number + 2); + } + } +} ``` ## python From 552388e8fdb3439fc3222cb0dafa02c48c0262f5 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 6 Jan 2022 13:58:34 +0800 Subject: [PATCH 002/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880059.?= =?UTF-8?q?=E8=9E=BA=E6=97=8B=E7=9F=A9=E9=98=B5II.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index c7e91b4d..3f7a59ca 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -287,6 +287,51 @@ var generateMatrix = function(n) { ``` +TypeScript: + +```typescript +function generateMatrix(n: number): number[][] { + let loopNum: number = Math.floor(n / 2); + const resArr: number[][] = new Array(n).fill(1).map(i => new Array(n)); + let chunkNum: number = n - 1; + let startX: number = 0; + let startY: number = 0; + let value: number = 1; + let x: number, y: number; + while (loopNum--) { + x = startX; + y = startY; + while (x < startX + chunkNum) { + resArr[y][x] = value; + x++; + value++; + } + while (y < startY + chunkNum) { + resArr[y][x] = value; + y++; + value++; + } + while (x > startX) { + resArr[y][x] = value; + x--; + value++; + } + while (y > startY) { + resArr[y][x] = value; + y--; + value++; + } + startX++; + startY++; + chunkNum -= 2; + } + if (n % 2 === 1) { + resArr[startX][startY] = value; + } + return resArr; +}; +``` + Go: ```go 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 003/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880206.?= =?UTF-8?q?=E7=BF=BB=E8=BD=AC=E9=93=BE=E8=A1=A8.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/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 004/257] =?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 b3711266156c2b8e25ac6e40b681842fefab9279 Mon Sep 17 00:00:00 2001 From: HanMengnan <1448189829@qq.com> Date: Tue, 11 Jan 2022 12:48:46 +0800 Subject: [PATCH 005/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=2034.=20=E5=9C=A8?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=85=83=E7=B4=A0=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=92=8C?= =?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA=E4=BD=8D=E7=BD=AE=20Go?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...排序数组中查找元素的第一个和最后一个位置.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index 2b96e41b..3f9cd747 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -389,6 +389,54 @@ class Solution: ### Go ```go +func searchRange(nums []int, target int) []int { + leftBorder := searchLeftBorder(nums, target) + rightBorder := searchRightBorder(nums, target) + + if leftBorder == -2 || rightBorder == -2 { // 情况一 + return []int{-1, -1} + } else if rightBorder-leftBorder > 1 { // 情况三 + return []int{leftBorder + 1, rightBorder - 1} + } else { // 情况二 + return []int{-1, -1} + } +} + +func searchLeftBorder(nums []int, target int) int { + left, right := 0, len(nums)-1 + leftBorder := -2 // 记录一下leftBorder没有被赋值的情况 + for left <= right { + middle := (left + right) / 2 + if target == nums[middle] { + right = middle - 1 + // 左边界leftBorder更新 + leftBorder = right + } else if target > nums[middle] { + left = middle + 1 + } else { + right = middle - 1 + } + } + return leftBorder +} + +func searchRightBorder(nums []int, target int) int { + left, right := 0, len(nums)-1 + rightBorder := -2 // 记录一下rightBorder没有被赋值的情况 + for left <= right { + middle := (left + right) / 2 + if target == nums[middle] { + left = middle + 1 + // 右边界rightBorder更新 + rightBorder = left + } else if target > nums[middle] { + left = middle + 1 + } else { + right = middle - 1 + } + } + return rightBorder +} ``` ### JavaScript From dfa64fa37b9493cfdf41a431d06da3565e86b1c5 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 11 Jan 2022 13:59:52 +0800 Subject: [PATCH 006/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880024.?= =?UTF-8?q?=E4=B8=A4=E4=B8=A4=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E8=8A=82=E7=82=B9.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/0024.两两交换链表中的节点.md | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 01abc7b4..bf1fd5e1 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -250,6 +250,38 @@ var swapPairs = function (head) { }; ``` +TypeScript: + +```typescript +function swapPairs(head: ListNode | null): ListNode | null { + /** + * 初始状态: + * curNode -> node1 -> node2 -> tmepNode + * 转换过程: + * curNode -> node2 + * curNode -> node2 -> node1 + * curNode -> node2 -> node1 -> tempNode + * curNode = node1 + */ + let retNode: ListNode | null = new ListNode(0, head), + curNode: ListNode | null = retNode, + node1: ListNode | null = null, + node2: ListNode | null = null, + tempNode: ListNode | null = null; + + while (curNode && curNode.next && curNode.next.next) { + node1 = curNode.next; + node2 = curNode.next.next; + tempNode = node2.next; + curNode.next = node2; + node2.next = node1; + node1.next = tempNode; + curNode = node1; + } + return retNode.next; +}; +``` + Kotlin: ```kotlin 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 007/257] =?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 0d2aacb400b106a0c1b3b72c769c7920951f5d05 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 11 Jan 2022 18:58:28 +0800 Subject: [PATCH 008/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880019.?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0?= =?UTF-8?q?=E7=AC=ACN=E4=B8=AA=E8=8A=82=E7=82=B9.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0019.删除链表的倒数第N个节点.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index e041937f..87ee6b12 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -181,7 +181,27 @@ var removeNthFromEnd = function(head, n) { return ret.next; }; ``` +TypeScript: + +```typescript +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { + let newHead: ListNode | null = new ListNode(0, head); + let slowNode: ListNode | null = newHead, + fastNode: ListNode | null = newHead; + for (let i = 0; i < n; i++) { + fastNode = fastNode.next; + } + while (fastNode.next) { + fastNode = fastNode.next; + slowNode = slowNode.next; + } + slowNode.next = slowNode.next.next; + return newHead.next; +}; +``` + Kotlin: + ```Kotlin fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { val pre = ListNode(0).apply { From 5b0b3daf2e65f88de0566aef47d74fa1a8b6aef2 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 11 Jan 2022 19:02:49 +0800 Subject: [PATCH 009/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0019.=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC?= =?UTF-8?q?N=E4=B8=AA=E8=8A=82=E7=82=B9.md)=EF=BC=9Atypescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=A2=9E=E5=8A=A0=E6=96=B0=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0019.删除链表的倒数第N个节点.md | 44 ++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 87ee6b12..813e9b02 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -183,6 +183,8 @@ var removeNthFromEnd = function(head, n) { ``` TypeScript: +版本一(快慢指针法): + ```typescript function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { let newHead: ListNode | null = new ListNode(0, head); @@ -200,6 +202,48 @@ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { }; ``` +版本二(计算节点总数法): + +```typescript +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { + let curNode: ListNode | null = head; + let listSize: number = 0; + while (curNode) { + curNode = curNode.next; + listSize++; + } + if (listSize === n) { + head = head.next; + } else { + curNode = head; + for (let i = 0; i < listSize - n - 1; i++) { + curNode = curNode.next; + } + curNode.next = curNode.next.next; + } + return head; +}; +``` + +版本三(递归倒退n法): + +```typescript +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { + let newHead: ListNode | null = new ListNode(0, head); + let cnt = 0; + function recur(node) { + if (node === null) return; + recur(node.next); + cnt++; + if (cnt === n + 1) { + node.next = node.next.next; + } + } + recur(newHead); + return newHead.next; +}; +``` + Kotlin: ```Kotlin From 4a611bbdd9884424fad04710e380f6549310cdd4 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Tue, 11 Jan 2022 19:07:15 +0800 Subject: [PATCH 010/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=2034.=20=E5=9C=A8?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84=E4=B8=AD=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=85=83=E7=B4=A0=E7=9A=84=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=92=8C?= =?UTF-8?q?=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA=E4=BD=8D=E7=BD=AE=20Go?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...排序数组中查找元素的第一个和最后一个位置.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index 2b96e41b..2ae8186a 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -389,6 +389,50 @@ class Solution: ### Go ```go +func searchRange(nums []int, target int) []int { + leftBorder := getLeft(nums, target) + rightBorder := getRight(nums, target) + // 情况一 + if leftBorder == -2 || rightBorder == -2 { + return []int{-1, -1} + } + // 情况三 + if rightBorder - leftBorder > 1 { + return []int{leftBorder + 1, rightBorder - 1} + } + // 情况二 + return []int{-1, -1} +} + +func getLeft(nums []int, target int) int { + left, right := 0, len(nums)-1 + border := -2 // 记录border没有被赋值的情况;这里不能赋值-1,target = num[0]时,会无法区分情况一和情况二 + for left <= right { // []闭区间 + mid := left + ((right - left) >> 1) + if nums[mid] >= target { // 找到第一个等于target的位置 + right = mid - 1 + border = right + } else { + left = mid + 1 + } + } + return border +} + +func getRight(nums []int, target int) int { + left, right := 0, len(nums) - 1 + border := -2 + for left <= right { + mid := left + ((right - left) >> 1) + if nums[mid] > target { + right = mid - 1 + } else { // 找到第一个大于target的位置 + left = mid + 1 + border = left + } + } + return border +} ``` ### JavaScript From a30d23871841797548b87ab1cc09ceda7be19bca Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 12 Jan 2022 00:29:24 +0800 Subject: [PATCH 011/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00283.=E7=A7=BB?= =?UTF-8?q?=E5=8A=A8=E9=9B=B6=20python=E4=B8=8D=E5=90=8C=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=8CGo=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0283.移动零.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0283.移动零.md b/problems/0283.移动零.md index 13b9c26c..bb75a696 100644 --- a/problems/0283.移动零.md +++ b/problems/0283.移动零.md @@ -89,9 +89,33 @@ Python: for i in range(slow, len(nums)): nums[i] = 0 ``` +交换前后变量,避免补零 +```python + def moveZeroes(self, nums: List[int]) -> None: + slow, fast = 0, 0 + while fast < len(nums): + if nums[fast] != 0: + nums[slow], nums[fast] = nums[fast], nums[slow] + slow += 1 # 保持[0, slow)区间是没有0的 + fast += 1 +``` Go: +```go +func moveZeroes(nums []int) { + slow := 0 + for fast := 0; fast < len(nums); fast ++ { + if nums[fast] != 0 { + temp := nums[slow] + nums[slow] = nums[fast] + nums[fast] = temp + slow++ + } + } +} +``` + JavaScript: ```javascript var moveZeroes = function(nums) { 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 012/257] =?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 ba8e46f241effbb7916bbe777d51c35ad529b4f1 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 12 Jan 2022 14:32:40 +0800 Subject: [PATCH 013/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E9=9D=A2?= =?UTF-8?q?=E8=AF=95=E9=A2=9802.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index e8198aa0..dd91f069 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -239,6 +239,43 @@ var getIntersectionNode = function(headA, headB) { }; ``` +TypeScript: + +```typescript +function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { + let sizeA: number = 0, + sizeB: number = 0; + let curA: ListNode | null = headA, + curB: ListNode | null = headB; + while (curA) { + sizeA++; + curA = curA.next; + } + while (curB) { + sizeB++; + curB = curB.next; + } + curA = headA; + curB = headB; + if (sizeA < sizeB) { + [sizeA, sizeB] = [sizeB, sizeA]; + [curA, curB] = [curB, curA]; + } + let gap = sizeA - sizeB; + while (gap-- && curA) { + curA = curA.next; + } + while (curA && curB) { + if (curA === curB) { + return curA; + } + curA = curA.next; + curB = curB.next; + } + return null; +}; +``` + C: ```c From e2ee3ea4501f75818d346b4613a4c3ab27c754ab Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 12 Jan 2022 16:25:53 +0800 Subject: [PATCH 014/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880142.?= =?UTF-8?q?=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8II.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0142.环形链表II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index dfe042b8..e8ca950d 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -294,7 +294,30 @@ var detectCycle = function(head) { }; ``` +TypeScript: + +```typescript +function detectCycle(head: ListNode | null): ListNode | null { + let slowNode: ListNode | null = head, + fastNode: ListNode | null = head; + while (fastNode !== null && fastNode.next !== null) { + slowNode = (slowNode as ListNode).next; + fastNode = fastNode.next.next; + if (slowNode === fastNode) { + slowNode = head; + while (slowNode !== fastNode) { + slowNode = (slowNode as ListNode).next; + fastNode = (fastNode as ListNode).next; + } + return slowNode; + } + } + return null; +}; +``` + Swift: + ```swift class Solution { func detectCycle(_ head: ListNode?) -> ListNode? { From 21fc5cd17bba8d75d22a56a832c19958610b28b2 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 12 Jan 2022 18:21:08 +0800 Subject: [PATCH 015/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880242.?= =?UTF-8?q?=E6=9C=89=E6=95=88=E7=9A=84=E5=AD=97=E6=AF=8D=E5=BC=82=E4=BD=8D?= =?UTF-8?q?=E8=AF=8D.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0242.有效的字母异位词.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index cdcf39ce..52f8e667 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -214,7 +214,23 @@ var isAnagram = function(s, t) { }; ``` +TypeScript: + +```typescript +function isAnagram(s: string, t: string): boolean { + if (s.length !== t.length) return false; + let helperArr: number[] = new Array(26).fill(0); + let pivot: number = 'a'.charCodeAt(0); + for (let i = 0, length = s.length; i < length; i++) { + helperArr[s.charCodeAt(i) - pivot]++; + helperArr[t.charCodeAt(i) - pivot]--; + } + return helperArr.every(i => i === 0); +}; +``` + Swift: + ```Swift func isAnagram(_ s: String, _ t: String) -> Bool { if s.count != t.count { 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 016/257] =?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 --- problems/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 +} +``` + -----------------------
From 0b643bd27d71a2472ee1cf0bfa16cd7f99df0a4b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 13 Jan 2022 15:00:39 +0800 Subject: [PATCH 017/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880349.?= =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86?= =?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/0349.两个数组的交集.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 812c4489..92342f17 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -190,7 +190,33 @@ var intersection = function(nums1, nums2) { }; ``` +TypeScript: + +版本一(正常解法): + +```typescript +function intersection(nums1: number[], nums2: number[]): number[] { + let resSet: Set = new Set(), + nums1Set: Set = new Set(nums1); + for (let i of nums2) { + if (nums1Set.has(i)) { + resSet.add(i); + } + } + return Array.from(resSet); +}; +``` + +版本二(秀操作): + +```typescript +function intersection(nums1: number[], nums2: number[]): number[] { + return Array.from(new Set(nums1.filter(i => nums2.includes(i)))) +}; +``` + Swift: + ```swift func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { var set1 = Set() From 391410a383f452c292a045e068b138295d4af7da Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 13 Jan 2022 15:29:20 +0800 Subject: [PATCH 018/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00202.=E5=BF=AB?= =?UTF-8?q?=E4=B9=90=E6=95=B0.md=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/0202.快乐数.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 2d678151..f0a46a40 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -232,7 +232,27 @@ var isHappy = function(n) { }; ``` +TypeScript: + +```typescript +function isHappy(n: number): boolean { + // Utils + // 计算val各位的平方和 + function calcSum(val: number): number { + return String(val).split("").reduce((pre, cur) => (pre + Number(cur) * Number(cur)), 0); + } + + let storeSet: Set = new Set(); + while (n !== 1 && !storeSet.has(n)) { + storeSet.add(n); + n = calcSum(n); + } + return n === 1; +}; +``` + Swift: + ```swift // number 每个位置上的数字的平方和 func getSum(_ number: Int) -> Int { From 6586f9a8299138d0e7fcb6135f68c75d67a36bdc Mon Sep 17 00:00:00 2001 From: weiting-cn <2254912@qq.com> Date: Thu, 13 Jan 2022 17:06:28 +0800 Subject: [PATCH 019/257] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E8=83=8C=E5=8C=85=E9=81=8D=E5=8E=86=E8=83=8C=E5=8C=85=E5=AE=B9?= =?UTF-8?q?=E9=87=8F=E6=97=B6=E7=9A=84=E8=BE=B9=E7=95=8C=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包问题理论基础完全背包.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index 3cc8557c..f79310b8 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -52,7 +52,7 @@ for(int i = 0; i < weight.size(); i++) { // 遍历物品 ```CPP // 先遍历物品,再遍历背包 for(int i = 0; i < weight.size(); i++) { // 遍历物品 - for(int j = weight[i]; j < bagWeight ; j++) { // 遍历背包容量 + for(int j = weight[i]; j <= bagWeight ; j++) { // 遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } From 97a0b8d46b9ffaf1174cde3ea01d2d2afda6a9fc Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 13 Jan 2022 19:18:32 +0800 Subject: [PATCH 020/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880001.?= =?UTF-8?q?=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 37c95736..b337d1e2 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -186,6 +186,24 @@ var twoSum = function (nums, target) { }; ``` +TypeScript: + +```typescript +function twoSum(nums: number[], target: number): number[] { + let helperMap: Map = new Map(); + let index: number | undefined; + let resArr: number[] = []; + for (let i = 0, length = nums.length; i < length; i++) { + index = helperMap.get(target - nums[i]); + if (index !== undefined) { + resArr = [i, index]; + } + helperMap.set(nums[i], i); + } + return resArr; +}; +``` + php ```php From ed2f56fa28817edbfccd3d3bc38f07eac71a5f2b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 13 Jan 2022 20:32:18 +0800 Subject: [PATCH 021/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880454.?= =?UTF-8?q?=E5=9B=9B=E6=95=B0=E7=9B=B8=E5=8A=A0II.md=EF=BC=89:=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/0454.四数相加II.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index 6853354c..352f693b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -139,7 +139,7 @@ class Solution(object): return count -``` +``` Go: ```go @@ -192,8 +192,33 @@ var fourSumCount = function(nums1, nums2, nums3, nums4) { }; ``` +TypeScript: + +```typescript +function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: number[]): number { + let helperMap: Map = new Map(); + let resNum: number = 0; + let tempVal: number | undefined; + for (let i of nums1) { + for (let j of nums2) { + tempVal = helperMap.get(i + j); + helperMap.set(i + j, tempVal ? tempVal + 1 : 1); + } + } + for (let k of nums3) { + for (let l of nums4) { + tempVal = helperMap.get(0 - (k + l)); + if (tempVal) { + resNum += tempVal; + } + } + } + return resNum; +}; +``` PHP: + ```php class Solution { /** From 3d36ecc092325ce614404d5cc1b69337153d1187 Mon Sep 17 00:00:00 2001 From: YiChih Wang Date: Thu, 13 Jan 2022 21:55:14 +0800 Subject: [PATCH 022/257] =?UTF-8?q?0452.=E7=94=A8=E6=9C=80=E5=B0=91?= =?UTF-8?q?=E6=95=B0=E9=87=8F=E7=9A=84=E7=AE=AD=E5=BC=95=E7=88=86=E6=B0=94?= =?UTF-8?q?=E7=90=83=20Rust=20=E8=AA=9E=E8=A8=80=E5=AF=A6=E7=8F=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0452.用最少数量的箭引爆气球.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index ebfe648f..33bbad55 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -239,5 +239,30 @@ int findMinArrowShots(int** points, int pointsSize, int* pointsColSize){ } ``` +### Rust +```Rust +use std::cmp; +impl Solution { + pub fn find_min_arrow_shots(mut points: Vec>) -> i32 { + if points.is_empty() { + return 0; + } + points.sort_by_key(|point| point[0]); + + let size = points.len(); + let mut count = 1; + + for i in 1..size { + if points[i][0] > points[i-1][1] { + count += 1; + } else { + points[i][1] = cmp::min(points[i][1], points[i-1][1]); + } + } + + return count; + } +} +``` -----------------------
From 7b785ab004eaa2635980a96ee543cbe65f4852de Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 13 Jan 2022 22:14:12 +0800 Subject: [PATCH 023/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880383.?= =?UTF-8?q?=E8=B5=8E=E9=87=91=E4=BF=A1.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/0383.赎金信.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 650f2a99..31e19b10 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -264,6 +264,27 @@ var canConstruct = function(ransomNote, magazine) { }; ``` +TypeScript: + +```typescript +function canConstruct(ransomNote: string, magazine: string): boolean { + let helperArr: number[] = new Array(26).fill(0); + let base: number = 'a'.charCodeAt(0); + let index: number; + for (let i = 0, length = magazine.length; i < length; i++) { + helperArr[magazine[i].charCodeAt(0) - base]++; + } + for (let i = 0, length = ransomNote.length; i < length; i++) { + index = ransomNote[i].charCodeAt(0) - base; + helperArr[index]--; + if (helperArr[index] < 0) { + return false; + } + } + return true; +}; +``` + PHP: ```php From 9d59aab89e5a61f752e67f3c969260a98a95fded Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 18:26:34 +0800 Subject: [PATCH 024/257] =?UTF-8?q?0028.=E5=AE=9E=E7=8E=B0strStr=EF=BC=9A?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index f0b56719..c23f5558 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -259,7 +259,7 @@ void getNext(int* next, const string& s) 然后还要对next数组进行初始化赋值,如下: -``` +```cpp int j = -1; next[0] = j; ``` @@ -278,8 +278,8 @@ next[i] 表示 i(包括i)之前最长相等的前后缀长度(其实就是 所以遍历模式串s的循环下标i 要从 1开始,代码如下: -``` -for(int i = 1; i < s.size(); i++) { +```cpp +for (int i = 1; i < s.size(); i++) { ``` 如果 s[i] 与 s[j+1]不相同,也就是遇到 前后缀末尾不相同的情况,就要向前回退。 @@ -292,7 +292,7 @@ next[j]就是记录着j(包括j)之前的子串的相同前后缀的长度 所以,处理前后缀不相同的情况代码如下: -``` +```cpp while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了     j = next[j]; // 向前回退 } @@ -300,7 +300,7 @@ while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了 3. 处理前后缀相同的情况 -如果s[i] 与 s[j + 1] 相同,那么就同时向后移动i 和j 说明找到了相同的前后缀,同时还要将j(前缀的长度)赋给next[i], 因为next[i]要记录相同前后缀的长度。 +如果 s[i] 与 s[j + 1] 相同,那么就同时向后移动i 和j 说明找到了相同的前后缀,同时还要将j(前缀的长度)赋给next[i], 因为next[i]要记录相同前后缀的长度。 代码如下: @@ -346,7 +346,7 @@ void getNext(int* next, const string& s){ i就从0开始,遍历文本串,代码如下: -``` +```cpp for (int i = 0; i < s.size(); i++)  ``` @@ -356,7 +356,7 @@ for (int i = 0; i < s.size(); i++)  代码如下: -``` +```cpp while(j >= 0 && s[i] != t[j + 1]) {     j = next[j]; } @@ -364,7 +364,7 @@ while(j >= 0 && s[i] != t[j + 1]) { 如果 s[i] 与 t[j + 1] 相同,那么i 和 j 同时向后移动, 代码如下: -``` +```cpp if (s[i] == t[j + 1]) {     j++; // i的增加在for循环里 } @@ -376,7 +376,7 @@ if (s[i] == t[j + 1]) { 代码如下: -``` +```cpp if (j == (t.size() - 1) ) {     return (i - t.size() + 1); } From 57af6f6a4b8941e5422c8387ab8591501c5f28f4 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 19:53:51 +0800 Subject: [PATCH 025/257] =?UTF-8?q?0027.=E7=A7=BB=E9=99=A4=E5=85=83?= =?UTF-8?q?=E7=B4=A0=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 99990302..d69f2bcf 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -42,7 +42,7 @@ ![27.移除元素-暴力解法](https://tva1.sinaimg.cn/large/008eGmZEly1gntrc7x9tjg30du09m1ky.gif) -很明显暴力解法的时间复杂度是O(n^2),这道题目暴力解法在leetcode上是可以过的。 +很明显暴力解法的时间复杂度是$O(n^2)$,这道题目暴力解法在leetcode上是可以过的。 代码如下: From 71ada4737a7cc00de5403c43f73a7d6c824eb7b2 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 19:54:34 +0800 Subject: [PATCH 026/257] =?UTF-8?q?=E6=A0=88=E4=B8=8E=E9=98=9F=E5=88=97?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/栈与队列理论基础.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/栈与队列理论基础.md b/problems/栈与队列理论基础.md index b9811b29..44fcbdd5 100644 --- a/problems/栈与队列理论基础.md +++ b/problems/栈与队列理论基础.md @@ -67,7 +67,7 @@ deque是一个双向队列,只要封住一段,只开通另一端就可以实 我们也可以指定vector为栈的底层实现,初始化语句如下: -``` +```cpp std::stack > third; // 使用vector为底层容器的栈 ``` @@ -77,7 +77,7 @@ std::stack > third; // 使用vector为底层容器的栈 也可以指定list 为起底层实现,初始化queue的语句如下: -``` +```cpp std::queue> third; // 定义以list为底层容器的队列 ``` From 13601e89abdff1a8b196645f647db551d8f4154e Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 20:13:03 +0800 Subject: [PATCH 027/257] =?UTF-8?q?0225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88=E3=80=810232.=E7=94=A8=E6=A0=88?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 2 +- problems/0232.用栈实现队列.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index fdb544a6..524ca329 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -46,7 +46,7 @@ 模拟的队列执行语句如下: -``` +```cpp queue.push(1); queue.push(2); queue.pop(); // 注意弹出的操作 diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 4edba2f2..0e4fce28 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -21,7 +21,7 @@ empty() -- 返回队列是否为空。 示例: -``` +```cpp MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); From cd4529c8ff7c4570a4541988c1cf3a76e3586150 Mon Sep 17 00:00:00 2001 From: bin3826246 <59920177+bin3826246@users.noreply.github.com> Date: Fri, 14 Jan 2022 19:15:00 +0800 Subject: [PATCH 028/257] =?UTF-8?q?Create=20=E9=9D=A2=E8=AF=95=E9=A2=98=20?= =?UTF-8?q?02.07.=20=E8=A7=A3=E6=B3=95=E6=9B=B4=E6=96=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题 02.07. 解法更新.md | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 problems/面试题 02.07. 解法更新.md diff --git a/problems/面试题 02.07. 解法更新.md b/problems/面试题 02.07. 解法更新.md new file mode 100644 index 00000000..119f875c --- /dev/null +++ b/problems/面试题 02.07. 解法更新.md @@ -0,0 +1,41 @@ +# 双指针,不计算链表长度 +设置指向headA和headB的指针pa、pb,分别遍历两个链表,每次循环同时更新pa和pb。 +* 当链表A遍历完之后,即pa为空时,将pa指向headB; +* 当链表B遍历完之后,即pa为空时,将pb指向headA; +* 当pa与pb相等时,即指向同一个节点,该节点即为相交起始节点。 +* 若链表不相交,则pa、pb同时为空时退出循环,即如果链表不相交,pa与pb在遍历过全部节点后同时指向结尾空节点,此时退出循环,返回空。 +# 证明思路 +设链表A不相交部分长度为a,链表B不相交部分长度为b,两个链表相交部分长度为c。
+在pa指向链表A时,即pa为空之前,pa经过链表A不相交部分和相交部分,走过的长度为a+c;
+pa指向链表B后,在移动相交节点之前经过链表B不相交部分,走过的长度为b,总合为a+c+b。
+同理,pb走过长度的总合为b+c+a。二者相等,即pa与pb可同时到达相交起始节点。
+该方法可避免计算具体链表长度。 +```cpp +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + //链表为空时,返回空指针 + if(headA == nullptr || headB == nullptr) return nullptr; + ListNode* pa = headA; + ListNode* pb = headB; + //pa与pb在遍历过全部节点后,同时指向结尾空节点时退出循环 + while(pa != nullptr || pb != nullptr){ + //pa为空时,将pa指向headB + if(pa == nullptr){ + pa = headB; + } + //pa为空时,将pb指向headA + if(pb == nullptr){ + pb = headA; + } + //pa == pb时,返回相交起始节点 + if(pa == pb){ + return pa; + } + pa = pa->next; + pb = pb->next; + } + return nullptr; + } +}; +``` From 570022f6666b633891bb9e590488529d5238d254 Mon Sep 17 00:00:00 2001 From: bin3826246 <59920177+bin3826246@users.noreply.github.com> Date: Fri, 14 Jan 2022 19:20:36 +0800 Subject: [PATCH 029/257] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=9802.07=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0cpp=E5=8F=8C=E6=8C=87=E9=92=88=E6=96=B0?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 双指针新解法,不需计算链表长度 --- problems/面试题 02.07. 解法更新.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/面试题 02.07. 解法更新.md b/problems/面试题 02.07. 解法更新.md index 119f875c..6115d02e 100644 --- a/problems/面试题 02.07. 解法更新.md +++ b/problems/面试题 02.07. 解法更新.md @@ -28,7 +28,7 @@ public: if(pb == nullptr){ pb = headA; } - //pa == pb时,返回相交起始节点 + //pa与pb相等时,返回相交起始节点 if(pa == pb){ return pa; } From 2ea72e3e4345e0de2feed93b4a74dd9bbbc25b68 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 14 Jan 2022 21:59:34 +0800 Subject: [PATCH 030/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880015.?= =?UTF-8?q?=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index c78ab06d..8992c5f4 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -332,7 +332,43 @@ var threeSum = function(nums) { return res; }; ``` +TypeScript: +```typescript +function threeSum(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + let length = nums.length; + let left: number = 0, + right: number = length - 1; + let resArr: number[][] = []; + for (let i = 0; i < length; i++) { + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + left = i + 1; + right = length - 1; + while (left < right) { + let total: number = nums[i] + nums[left] + nums[right]; + if (total === 0) { + resArr.push([nums[i], nums[left], nums[right]]); + left++; + right--; + while (nums[right] === nums[right + 1]) { + right--; + } + while (nums[left] === nums[left - 1]) { + left++; + } + } else if (total < 0) { + left++; + } else { + right--; + } + } + } + return resArr; +}; +``` ruby: ```ruby From 12bf8ae05b176816a21cfd741b2274bfada14aae Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 14 Jan 2022 22:36:55 +0800 Subject: [PATCH 031/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880018.?= =?UTF-8?q?=E5=9B=9B=E6=95=B0=E4=B9=8B=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index b94ebeef..dae8636b 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -311,7 +311,49 @@ var fourSum = function(nums, target) { }; ``` +TypeScript: + +```typescript +function fourSum(nums: number[], target: number): number[][] { + nums.sort((a, b) => a - b); + let first: number = 0, + second: number, + third: number, + fourth: number; + let length: number = nums.length; + let resArr: number[][] = []; + for (; first < length; first++) { + if (first > 0 && nums[first] === nums[first - 1]) { + continue; + } + for (second = first + 1; second < length; second++) { + if ((second - first) > 1 && nums[second] === nums[second - 1]) { + continue; + } + third = second + 1; + fourth = length - 1; + while (third < fourth) { + let total: number = nums[first] + nums[second] + nums[third] + nums[fourth]; + if (total === target) { + resArr.push([nums[first], nums[second], nums[third], nums[fourth]]); + third++; + fourth--; + while (nums[third] === nums[third - 1]) third++; + while (nums[fourth] === nums[fourth + 1]) fourth--; + } else if (total < target) { + third++; + } else { + fourth--; + } + } + } + } + return resArr; +}; +``` + PHP: + ```php class Solution { /** From d9ffaec8a8e6b630f187ec662917b53d2878aee8 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 15 Jan 2022 16:32:29 +0800 Subject: [PATCH 032/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880344.?= =?UTF-8?q?=E5=8F=8D=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.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/0344.反转字符串.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 28313839..e6a56ca5 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -201,6 +201,27 @@ var reverseString = function(s) { }; ``` +TypeScript: + +```typescript +/** + Do not return anything, modify s in-place instead. + */ +function reverseString(s: string[]): void { + let length: number = s.length; + let left: number = 0, + right: number = length - 1; + let tempStr: string; + while (left < right) { + tempStr = s[left]; + s[left] = s[right]; + s[right] = tempStr; + left++; + right--; + } +}; +``` + Swift: ```swift From 91807bfe9deb35788886786dd1590044dd707a36 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 15 Jan 2022 17:32:13 +0800 Subject: [PATCH 033/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0541.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II.md):=20=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/0541.反转字符串II.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index fb92b1e4..77558663 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -252,6 +252,28 @@ var reverseStr = function(s, k) { ``` +TypeScript: + +```typescript +function reverseStr(s: string, k: number): string { + let left: number, right: number; + let arr: string[] = s.split(''); + let temp: string; + for (let i = 0, length = arr.length; i < length; i += 2 * k) { + left = i; + right = (i + k - 1) >= length ? length - 1 : i + k - 1; + while (left < right) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } + return arr.join(''); +}; +``` + Swift: ```swift From 3d7ec66e21c511f5cd0440388de9075ac5d45155 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 15 Jan 2022 17:59:35 +0800 Subject: [PATCH 034/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E5=89=91?= =?UTF-8?q?=E6=8C=87Offer05.=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index d0f382c8..530545fb 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -298,6 +298,33 @@ javaScript: }; ``` +TypeScript: + +```typescript +function replaceSpace(s: string): string { + let arr: string[] = s.split(''); + let spaceNum: number = 0; + let oldLength: number = arr.length; + for (let i = 0; i < oldLength; i++) { + if (arr[i] === ' ') { + spaceNum++; + } + } + arr.length = oldLength + 2 * spaceNum; + let cur: number = oldLength - 1; + for (let i = arr.length - 1; i >= 0; i--, cur--) { + if (arr[cur] !== ' ') { + arr[i] = arr[cur] + } else { + arr[i] = '0'; + arr[--i] = '2'; + arr[--i] = '%'; + } + } + return arr.join(''); +}; +``` + Swift: ```swift From d164c86ac418de56e18ab6edb7578e896d5cb892 Mon Sep 17 00:00:00 2001 From: zhangjiong Date: Mon, 17 Jan 2022 01:23:41 +0800 Subject: [PATCH 035/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200344.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=20C#=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0344.反转字符串.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 9176c915..920cd86c 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -232,6 +232,19 @@ void reverseString(char* s, int sSize){ } ``` +C#: +```csharp +public class Solution +{ + public void ReverseString(char[] s) + { + for (int i = 0, j = s.Length - 1; i < j; i++, j--) + { + (s[i], s[j]) = (s[j], s[i]); + } + } +} +``` -----------------------
From 1f00889410d44ab517b7cdd76ace801b18ed7361 Mon Sep 17 00:00:00 2001 From: zhangjiong Date: Mon, 17 Jan 2022 01:30:46 +0800 Subject: [PATCH 036/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200541.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II=20C#=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index fb92b1e4..1338cd0d 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -272,9 +272,21 @@ func reverseStr(_ s: String, _ k: Int) -> String { } ``` - - - +C#: +```csharp +public class Solution +{ + public string ReverseStr(string s, int k) + { + Span span = s.ToCharArray().AsSpan(); + for (int i = 0; i < span.Length; i += 2 * k) + { + span[i + k < span.Length ? i..(i + k) : i..].Reverse(); + } + return span.ToString(); + } +} +``` -----------------------
From b1a0fbad2b4799416bd45a297f67df93eca4612b Mon Sep 17 00:00:00 2001 From: zhangjiong Date: Mon, 17 Jan 2022 11:53:23 +0800 Subject: [PATCH 037/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200015.=E4=B8=89?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20C#=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index c78ab06d..19e19e43 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -509,5 +509,64 @@ int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes } ``` +C#: +```csharp +public class Solution +{ + public IList> ThreeSum(int[] nums) + { + var result = new List>(); + + Array.Sort(nums); + + for (int i = 0; i < nums.Length - 2; i++) + { + int n1 = nums[i]; + + if (n1 > 0) + break; + + if (i > 0 && n1 == nums[i - 1]) + continue; + + int left = i + 1; + int right = nums.Length - 1; + + while (left < right) + { + int n2 = nums[left]; + int n3 = nums[right]; + int sum = n1 + n2 + n3; + + if (sum > 0) + { + right--; + } + else if (sum < 0) + { + left++; + } + else + { + result.Add(new List { n1, n2, n3 }); + + while (left < right && nums[left] == n2) + { + left++; + } + + while (left < right && nums[right] == n3) + { + right--; + } + } + } + } + + return result; + } +} +``` + -----------------------
From 35bbec3e298c03cc69582f486baa961102e0f583 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Mon, 17 Jan 2022 12:36:22 +0800 Subject: [PATCH 038/257] Update --- problems/0063.不同路径II.md | 29 +++++----- problems/0096.不同的二叉搜索树.md | 10 ++-- problems/0343.整数拆分.md | 26 ++++----- problems/背包理论基础01背包-1.md | 88 +++++++++++++++---------------- 4 files changed, 75 insertions(+), 78 deletions(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 490b6b5c..1bcc11cd 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -4,7 +4,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 63. 不同路径 II +# 63. 不同路径 II [力扣题目链接](https://leetcode-cn.com/problems/unique-paths-ii/) @@ -22,23 +22,22 @@ ![](https://img-blog.csdnimg.cn/20210111204939971.png) -输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] -输出:2 +* 输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] +* 输出:2 解释: -3x3 网格的正中间有一个障碍物。 -从左上角到右下角一共有 2 条不同的路径: -1. 向右 -> 向右 -> 向下 -> 向下 -2. 向下 -> 向下 -> 向右 -> 向右 +* 3x3 网格的正中间有一个障碍物。 +* 从左上角到右下角一共有 2 条不同的路径: + 1. 向右 -> 向右 -> 向下 -> 向下 + 2. 向下 -> 向下 -> 向右 -> 向右 示例 2: ![](https://img-blog.csdnimg.cn/20210111205857918.png) -输入:obstacleGrid = [[0,1],[0,0]] -输出:1 +* 输入:obstacleGrid = [[0,1],[0,0]] +* 输出:1 提示: - * m == obstacleGrid.length * n == obstacleGrid[i].length * 1 <= m, n <= 100 @@ -171,7 +170,7 @@ public: ## 其他语言版本 -Java: +### Java ```java class Solution { @@ -199,7 +198,7 @@ class Solution { ``` -Python: +### Python ```python class Solution: @@ -262,7 +261,7 @@ class Solution: ``` -Go: +### Go ```go func uniquePathsWithObstacles(obstacleGrid [][]int) int { @@ -308,8 +307,8 @@ func uniquePathsWithObstacles(obstacleGrid [][]int) int { ``` -Javascript -``` Javascript +### Javascript +```Javascript var uniquePathsWithObstacles = function(obstacleGrid) { const m = obstacleGrid.length const n = obstacleGrid[0].length diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index d4b8d024..48826697 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -4,7 +4,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 96.不同的二叉搜索树 +# 96.不同的二叉搜索树 [力扣题目链接](https://leetcode-cn.com/problems/unique-binary-search-trees/) @@ -163,7 +163,7 @@ public: ## 其他语言版本 -Java: +### Java ```Java class Solution { public int numTrees(int n) { @@ -184,7 +184,7 @@ class Solution { } ``` -Python: +### Python ```python class Solution: def numTrees(self, n: int) -> int: @@ -196,7 +196,7 @@ class Solution: return dp[-1] ``` -Go: +### Go ```Go func numTrees(n int)int{ dp:=make([]int,n+1) @@ -210,7 +210,7 @@ func numTrees(n int)int{ } ``` -Javascript: +### Javascript ```Javascript const numTrees =(n) => { let dp = new Array(n+1).fill(0); diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 5d11f670..471a7ab7 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -4,23 +4,22 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 343. 整数拆分 +# 343. 整数拆分 [力扣题目链接](https://leetcode-cn.com/problems/integer-break/) 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 示例 1: -输入: 2 -输出: 1 - -\解释: 2 = 1 + 1, 1 × 1 = 1。 +* 输入: 2 +* 输出: 1 +* 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: -输入: 10 -输出: 36 -解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 -说明: 你可以假设 n 不小于 2 且不大于 58。 +* 输入: 10 +* 输出: 36 +* 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 +* 说明: 你可以假设 n 不小于 2 且不大于 58。 ## 思路 @@ -193,7 +192,7 @@ public: ## 其他语言版本 -Java: +### Java ```Java class Solution { public int integerBreak(int n) { @@ -212,7 +211,7 @@ class Solution { } ``` -Python: +### Python ```python class Solution: def integerBreak(self, n: int) -> int: @@ -226,7 +225,8 @@ class Solution: dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])) return dp[n] ``` -Go: + +### Go ```golang func integerBreak(n int) int { /** @@ -256,7 +256,7 @@ func max(a,b int) int{ } ``` -Javascript: +### Javascript ```Javascript var integerBreak = function(n) { let dp = new Array(n + 1).fill(0) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 4367aff9..6ff32017 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -3,11 +3,12 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ # 动态规划:关于01背包问题,你该了解这些! 这周我们正式开始讲解背包问题! -背包问题的经典资料当然是:背包九讲。在公众号「代码随想录」后台回复:背包九讲,就可以获得背包九讲的PDF。 +背包问题的经典资料当然是:背包九讲。在公众号「代码随想录」后台回复:背包九讲,就可以获得背包九讲的pdf。 但说实话,背包九讲对于小白来说确实不太友好,看起来还是有点费劲的,而且都是伪代码理解起来也吃力。 @@ -32,7 +33,7 @@ leetcode上没有纯01背包的问题,都是01背包应用方面的题目, ## 01 背包 -有N件物品和一个最多能背重量为W 的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。**每件物品只能用一次**,求解将哪些物品装入背包里物品价值总和最大。 +有n件物品和一个最多能背重量为w 的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。**每件物品只能用一次**,求解将哪些物品装入背包里物品价值总和最大。 ![动态规划-背包问题](https://img-blog.csdnimg.cn/20210117175428387.jpg) @@ -40,7 +41,7 @@ leetcode上没有纯01背包的问题,都是01背包应用方面的题目, 这样其实是没有从底向上去思考,而是习惯性想到了背包,那么暴力的解法应该是怎么样的呢? -每一件物品其实只有两个状态,取或者不取,所以可以使用回溯法搜索出所有的情况,那么时间复杂度就是$O(2^n)$,这里的n表示物品数量。 +每一件物品其实只有两个状态,取或者不取,所以可以使用回溯法搜索出所有的情况,那么时间复杂度就是$o(2^n)$,这里的n表示物品数量。 **所以暴力的解法是指数级别的时间复杂度。进而才需要动态规划的解法来进行优化!** @@ -109,7 +110,7 @@ for (int j = 0 ; j < weight[0]; j++) { // 当然这一步,如果把dp数组 dp[0][j] = 0; } // 正序遍历 -for (int j = weight[0]; j <= bagWeight; j++) { +for (int j = weight[0]; j <= bagweight; j++) { dp[0][j] = value[0]; } ``` @@ -135,8 +136,8 @@ dp[0][j] 和 dp[i][0] 都已经初始化了,那么其他下标应该初始化 ``` // 初始化 dp -vector> dp(weight.size(), vector(bagWeight + 1, 0)); -for (int j = weight[0]; j <= bagWeight; j++) { +vector> dp(weight.size(), vector(bagweight + 1, 0)); +for (int j = weight[0]; j <= bagweight; j++) { dp[0][j] = value[0]; } @@ -160,7 +161,7 @@ for (int j = weight[0]; j <= bagWeight; j++) { ``` // weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 - for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 + for(int j = 0; j <= bagweight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); @@ -174,7 +175,7 @@ for(int i = 1; i < weight.size(); i++) { // 遍历物品 ``` // weight数组的大小 就是物品个数 -for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 +for(int j = 0; j <= bagweight; j++) { // 遍历背包容量 for(int i = 1; i < weight.size(); i++) { // 遍历物品 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); @@ -219,32 +220,32 @@ dp[i-1][j]和dp[i - 1][j - weight[i]] 都在dp[i][j]的左上角方向(包括 主要就是自己没有动手推导一下dp数组的演变过程,如果推导明白了,代码写出来就算有问题,只要把dp数组打印出来,对比一下和自己推导的有什么差异,很快就可以发现问题了。 -## 完整C++测试代码 +## 完整c++测试代码 -```CPP +```cpp void test_2_wei_bag_problem1() { vector weight = {1, 3, 4}; vector value = {15, 20, 30}; - int bagWeight = 4; + int bagweight = 4; // 二维数组 - vector> dp(weight.size(), vector(bagWeight + 1, 0)); + vector> dp(weight.size(), vector(bagweight + 1, 0)); // 初始化 - for (int j = weight[0]; j <= bagWeight; j++) { + for (int j = weight[0]; j <= bagweight; j++) { dp[0][j] = value[0]; } // weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 - for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 + for(int j = 0; j <= bagweight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } - cout << dp[weight.size() - 1][bagWeight] << endl; + cout << dp[weight.size() - 1][bagweight] << endl; } int main() { @@ -267,48 +268,45 @@ int main() { ## 其他语言版本 -Java: +### java ```java - public static void main(String[] args) { + public static void main(string[] args) { int[] weight = {1, 3, 4}; int[] value = {15, 20, 30}; - int bagSize = 4; - testWeightBagProblem(weight, value, bagSize); + int bagsize = 4; + testweightbagproblem(weight, value, bagsize); } - public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ - int wLen = weight.length, value0 = 0; + public static void testweightbagproblem(int[] weight, int[] value, int bagsize){ + int wlen = weight.length, value0 = 0; //定义dp数组:dp[i][j]表示背包容量为j时,前i个物品能获得的最大价值 - int[][] dp = new int[wLen + 1][bagSize + 1]; + int[][] dp = new int[wlen + 1][bagsize + 1]; //初始化:背包容量为0时,能获得的价值都为0 - for (int i = 0; i <= wLen; i++){ + for (int i = 0; i <= wlen; i++){ dp[i][0] = value0; } //遍历顺序:先遍历物品,再遍历背包容量 - for (int i = 1; i <= wLen; i++){ - for (int j = 1; j <= bagSize; j++){ + for (int i = 1; i <= wlen; i++){ + for (int j = 1; j <= bagsize; j++){ if (j < weight[i - 1]){ dp[i][j] = dp[i - 1][j]; }else{ - dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]); + dp[i][j] = math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]); } } } //打印dp数组 - for (int i = 0; i <= wLen; i++){ - for (int j = 0; j <= bagSize; j++){ - System.out.print(dp[i][j] + " "); + for (int i = 0; i <= wlen; i++){ + for (int j = 0; j <= bagsize; j++){ + system.out.print(dp[i][j] + " "); } - System.out.print("\n"); + system.out.print("\n"); } } ``` - - - -Python: +### python ```python def test_2_wei_bag_problem1(bag_size, weight, value) -> int: rows, cols = len(weight), bag_size + 1 @@ -343,26 +341,26 @@ if __name__ == "__main__": ``` -Go: +### go ```go -func test_2_wei_bag_problem1(weight, value []int, bagWeight int) int { +func test_2_wei_bag_problem1(weight, value []int, bagweight int) int { // 定义dp数组 dp := make([][]int, len(weight)) for i, _ := range dp { - dp[i] = make([]int, bagWeight+1) + dp[i] = make([]int, bagweight+1) } // 初始化 - for j := bagWeight; j >= weight[0]; j-- { + for j := bagweight; j >= weight[0]; j-- { dp[0][j] = dp[0][j-weight[0]] + value[0] } // 递推公式 for i := 1; i < len(weight); i++ { //正序,也可以倒序 - for j := weight[i];j<= bagWeight ; j++ { + for j := weight[i];j<= bagweight ; j++ { dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]) } } - return dp[len(weight)-1][bagWeight] + return dp[len(weight)-1][bagweight] } func max(a,b int) int { @@ -379,19 +377,19 @@ func main() { } ``` -javaScript: +### javascript ```js -function testWeightBagProblem (wight, value, size) { +function testweightbagproblem (wight, value, size) { const len = wight.length, - dp = Array.from({length: len + 1}).map( - () => Array(size + 1).fill(0) + dp = array.from({length: len + 1}).map( + () => array(size + 1).fill(0) ); for(let i = 1; i <= len; i++) { for(let j = 0; j <= size; j++) { if(wight[i - 1] <= j) { - dp[i][j] = Math.max( + dp[i][j] = math.max( dp[i - 1][j], value[i - 1] + dp[i - 1][j - wight[i - 1]] ) From e4537379854fc4943f7d0a48df9168dd647f8ba8 Mon Sep 17 00:00:00 2001 From: zhangjiong Date: Mon, 17 Jan 2022 15:17:23 +0800 Subject: [PATCH 039/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200018.=E5=9B=9B?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20C#=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index b94ebeef..0a04cd68 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -403,5 +403,67 @@ func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { } ``` +C#: +```csharp +public class Solution +{ + public IList> FourSum(int[] nums, int target) + { + var result = new List>(); + + Array.Sort(nums); + + for (int i = 0; i < nums.Length - 3; i++) + { + int n1 = nums[i]; + if (i > 0 && n1 == nums[i - 1]) + continue; + + for (int j = i + 1; j < nums.Length - 2; j++) + { + int n2 = nums[j]; + if (j > i + 1 && n2 == nums[j - 1]) + continue; + + int left = j + 1; + int right = nums.Length - 1; + + while (left < right) + { + int n3 = nums[left]; + int n4 = nums[right]; + int sum = n1 + n2 + n3 + n4; + + if (sum > target) + { + right--; + } + else if (sum < target) + { + left++; + } + else + { + result.Add(new List { n1, n2, n3, n4 }); + + while (left < right && nums[left] == n3) + { + left++; + } + + while (left < right && nums[right] == n4) + { + right--; + } + } + } + } + } + + return result; + } +} +``` + -----------------------
From d941915829f122e717190d3712d1fba7b3fbde32 Mon Sep 17 00:00:00 2001 From: chengleqi Date: Mon, 17 Jan 2022 22:07:48 +0800 Subject: [PATCH 040/257] =?UTF-8?q?update=200051.N=E7=9A=87=E5=90=8E.md=20?= =?UTF-8?q?Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 109 ++++++++++++++++++----------------------- 1 file changed, 48 insertions(+), 61 deletions(-) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 51415e88..7eb0d7a0 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -346,69 +346,56 @@ class Solution { ### Go ```Go -import "strings" -var res [][]string - -func isValid(board [][]string, row, col int) (res bool){ - n := len(board) - for i:=0; i < row; i++ { - if board[i][col] == "Q" { - return false - } - } - for i := 0; i < n; i++{ - if board[row][i] == "Q" { - return false - } - } - - for i ,j := row, col; i >= 0 && j >=0 ; i, j = i - 1, j- 1{ - if board[i][j] == "Q"{ - return false - } - } - for i, j := row, col; i >=0 && j < n; i,j = i-1, j+1 { - if board[i][j] == "Q" { - return false - } - } - return true -} - -func backtrack(board [][]string, row int) { - size := len(board) - if row == size{ - temp := make([]string, size) - for i := 0; i= 0 && j >= 0; i, j = i-1, j-1 { + if chessboard[i][j] == "Q" { + return false + } + } + for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 { + if chessboard[i][j] == "Q" { + return false + } + } + return true } ``` ### Javascript From a2ac3fa4310f001758f6e08d8874164932ca4f04 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 18 Jan 2022 13:00:33 +0800 Subject: [PATCH 041/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880151.?= =?UTF-8?q?=E7=BF=BB=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E8=AF=8D.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0151.翻转字符串里的单词.md | 59 +++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 48324cd9..fc25c718 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -553,6 +553,65 @@ function reverse(strArr, start, end) { } ``` +TypeScript: + +```typescript +function reverseWords(s: string): string { + /** Utils **/ + // 删除多余空格, 如' hello world ' => 'hello world' + function delExtraSpace(arr: string[]): void { + let left: number = 0, + right: number = 0, + length: number = arr.length; + while (right < length && arr[right] === ' ') { + right++; + } + while (right < length) { + if (arr[right] === ' ' && arr[right - 1] === ' ') { + right++; + continue; + } + arr[left++] = arr[right++]; + } + if (arr[left - 1] === ' ') { + arr.length = left - 1; + } else { + arr.length = left; + } + } + // 翻转字符串,如:'hello' => 'olleh' + function reverseWords(strArr: string[], start: number, end: number) { + let temp: string; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + + /** Main code **/ + let strArr: string[] = s.split(''); + delExtraSpace(strArr); + let length: number = strArr.length; + // 翻转整个字符串 + reverseWords(strArr, 0, length - 1); + let start: number = 0, + end: number = 0; + while (start < length) { + end = start; + while (strArr[end] !== ' ' && end < length) { + end++; + } + // 翻转单个单词 + reverseWords(strArr, start, end - 1); + start = end + 1; + } + return strArr.join(''); +}; +``` + Swift: ```swift From 3d0ce431d83ac814ab8479d9392c6a6e5e022366 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, 18 Jan 2022 13:18:36 +0800 Subject: [PATCH 042/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20110.=E5=B9=B3?= =?UTF-8?q?=E8=A1=A1=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/0110.平衡二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index c0914f05..9d43407a 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -730,5 +730,33 @@ bool isBalanced(struct TreeNode* root){ } ``` +## Swift: + +>递归 +```swift +func isBalanced(_ root: TreeNode?) -> Bool { + // -1 已经不是平衡二叉树 + return getHeight(root) == -1 ? false : true +} +func getHeight(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + let leftHeight = getHeight(root.left) + if leftHeight == -1 { + return -1 + } + let rightHeight = getHeight(root.right) + if rightHeight == -1 { + return -1 + } + if abs(leftHeight - rightHeight) > 1 { + return -1 + } else { + return 1 + max(leftHeight, rightHeight) + } +} +``` + -----------------------
From d1a5c9cc908e78ffdb82f5acf6a2ff297254e2fa Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 18 Jan 2022 13:25:50 +0800 Subject: [PATCH 043/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E5=89=91?= =?UTF-8?q?=E6=8C=87Offer58-II.=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer58-II.左旋转字符串.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index c391d661..2fbd2888 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -209,6 +209,31 @@ var reverseLeftWords = function(s, n) { }; ``` +TypeScript: + +```typescript +function reverseLeftWords(s: string, n: number): string { + /** Utils */ + function reverseWords(strArr: string[], start: number, end: number): void { + let temp: string; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + /** Main code */ + let strArr: string[] = s.split(''); + let length: number = strArr.length; + reverseWords(strArr, 0, length - 1); + reverseWords(strArr, 0, length - n - 1); + reverseWords(strArr, length - n, length - 1); + return strArr.join(''); +}; +``` + Swift: ```swift From 76893360a9bc77a61ac0f620441680f4ba56a3d9 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 18 Jan 2022 13:30:39 +0800 Subject: [PATCH 044/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E5=89=91?= =?UTF-8?q?=E6=8C=87Offer58-II.=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2.md=EF=BC=89=EF=BC=9AJS=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=96=B0=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer58-II.左旋转字符串.md | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 2fbd2888..61391274 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -209,6 +209,36 @@ var reverseLeftWords = function(s, n) { }; ``` +版本二(在原字符串上操作): + +```js +/** + * @param {string} s + * @param {number} n + * @return {string} + */ +var reverseLeftWords = function (s, n) { + /** Utils */ + function reverseWords(strArr, start, end) { + let temp; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + /** Main code */ + let strArr = s.split(''); + let length = strArr.length; + reverseWords(strArr, 0, length - 1); + reverseWords(strArr, 0, length - n - 1); + reverseWords(strArr, length - n, length - 1); + return strArr.join(''); +}; +``` + TypeScript: ```typescript From 5a3be18f127f97bce75a45e473381d1fe3206a94 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:18:56 +0800 Subject: [PATCH 045/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00844.=E6=AF=94?= =?UTF-8?q?=E8=BE=83=E5=90=AB=E9=80=80=E6=A0=BC=E7=9A=84=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20python=20go=E5=8F=8C=E6=8C=87=E9=92=88=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/0844.比较含退格的字符串.md | 81 +++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 5d629a8c..00d52e42 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -205,6 +205,42 @@ class Solution: return self.get_string(s) == self.get_string(t) pass ``` +双指针 +```python +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + s_index, t_index = len(s) - 1, len(t) - 1 + s_backspace, t_backspace = 0, 0 # 记录s,t的#数量 + while s_index >= 0 or t_index >= 0: # 使用or,以防长度不一致 + while s_index >= 0: # 从后向前,消除s的# + if s[s_index] == '#': + s_index -= 1 + s_backspace += 1 + else: + if s_backspace > 0: + s_index -= 1 + s_backspace -= 1 + else: + break + while t_index >= 0: # 从后向前,消除t的# + if t[t_index] == '#': + t_index -= 1 + t_backspace += 1 + else: + if t_backspace > 0: + t_index -= 1 + t_backspace -= 1 + else: + break + if s_index >= 0 and t_index >= 0: # 后半部分#消除完了,接下来比较当前位的值 + if s[s_index] != t[t_index]: + return False + elif s_index >= 0 or t_index >= 0: # 一个字符串找到了待比较的字符,另一个没有,返回False + return False + s_index -= 1 + t_index -= 1 + return True +``` ### Go @@ -226,6 +262,51 @@ func backspaceCompare(s string, t string) bool { return getString(s) == getString(t) } +``` +双指针 +```go +func backspaceCompare(s string, t string) bool { + s_index, t_index := len(s) - 1, len(t) - 1 + s_backspace, t_backspace := 0, 0 // 记录s,t的#数量 + for s_index >= 0 || t_index >= 0 { // 使用or,以防长度不一致 + for s_index >= 0 { // 从后向前,消除s的# + if s[s_index] == '#' { + s_index-- + s_backspace++ + } else { + if s_backspace > 0 { + s_index-- + s_backspace-- + } else { + break + } + } + } + for t_index >= 0 { // 从后向前,消除t的# + if t[t_index] == '#' { + t_index-- + t_backspace++ + } else { + if t_backspace > 0 { + t_index-- + t_backspace-- + } else { + break + } + } + } + if s_index >= 0 && t_index >= 0 { // 后半部分#消除完了,接下来比较当前位的值 + if s[s_index] != t[t_index] { + return false + } + } else if s_index >= 0 || t_index >= 0 { // 一个字符串找到了待比较的字符,另一个没有,返回false + return false + } + s_index-- + t_index-- + } + return true +} ``` ### JavaScript From da4f5de90905e87e6804ca6c172750c9fc5e4370 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:32:28 +0800 Subject: [PATCH 046/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00054.=E8=9E=BA?= =?UTF-8?q?=E6=97=8B=E7=9F=A9=E9=98=B5=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0054.螺旋矩阵.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 3f85c607..ccf6f471 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -131,7 +131,46 @@ public: * [59.螺旋矩阵II](https://leetcode-cn.com/problems/spiral-matrix-ii/) * [剑指Offer 29.顺时针打印矩阵](https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/) +## 其他语言版本 +Python: +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + left, right, up, down = 0, n - 1, 0, m - 1 # 定位四个方向的边界,闭区间 + res = [] + + while True: + for i in range(left, right + 1): # 上边,从左到右 + res.append(matrix[up][i]) + up += 1 # 上边界下移 + if len(res) >= m * n: # 判断是否已经遍历完 + break + + for i in range(up, down + 1): # 右边,从上到下 + res.append(matrix[i][right]) + right -= 1 # 右边界左移 + + if len(res) >= m * n: + break + + for i in range(right, left - 1, -1): # 下边,从右到左 + res.append(matrix[down][i]) + down -= 1 # 下边界上移 + + if len(res) >= m * n: + break + + for i in range(down, up - 1, -1): # 左边,从下到上 + res.append(matrix[i][left]) + left += 1 # 左边界右移 + + if len(res) >= m * n: + break + + return res +``` -----------------------
From 850939e40745fb6cf03c056caf0dbb88cae620ec Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:48:45 +0800 Subject: [PATCH 047/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=20python=20go=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/链表理论基础.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index 109aa1ed..a4fefa2b 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -195,10 +195,20 @@ class ListNode { ``` Python: - +```python +class ListNode: + def __init__(self, val, next=None): + self.val = val + self.next = next +``` Go: - +```go +type ListNode struct { + Val int + Next *ListNode +} +``` From b124befd1263689d1078a3417cd10cbf5ce2aebe Mon Sep 17 00:00:00 2001 From: chenhaoran14 <2718827494@qq.com> Date: Thu, 20 Jan 2022 01:15:23 +0800 Subject: [PATCH 048/257] =?UTF-8?q?=E5=AF=B9Java=E7=9A=84=E5=A4=A7?= =?UTF-8?q?=E9=A1=B6=E5=A0=86=E5=92=8C=E5=B0=8F=E9=A1=B6=E5=A0=86=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E8=BF=9B=E8=A1=8C=E4=BA=86=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 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 0b8fd2d7..8bd774e9 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) -> o2.getValue() - o1.getValue()); + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); for (Map.Entry entry : entries) { queue.offer(entry); if (queue.size() > k) { From baff8206d5a6bbb0a66b0db938fca36139bd0e10 Mon Sep 17 00:00:00 2001 From: weiting-cn <2254912@qq.com> Date: Thu, 20 Jan 2022 11:36:17 +0800 Subject: [PATCH 049/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20(0583.=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=93=8D=E4=BD=9C.md)=20:=20=E5=A2=9E=E5=8A=A0=E8=A7=A3?= =?UTF-8?q?=E9=A2=98=E6=80=9D=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0583.两个字符串的删除操作.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index d2f7d84b..53c1a125 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -18,6 +18,8 @@ ## 思路 +### 动态规划一 + 本题和[动态规划:115.不同的子序列](https://programmercarl.com/0115.不同的子序列.html)相比,其实就是两个字符串都可以删除了,情况虽说复杂一些,但整体思路是不变的。 这次是两个字符串可以相互删了,这种题目也知道用动态规划的思路来解,动规五部曲,分析如下: @@ -98,6 +100,29 @@ public: ``` +### 动态规划二 + +本题和[动态规划:1143.最长公共子序列](https://programmercarl.com/1143.最长公共子序列.html)基本相同,只要求出两个字符串的最长公共子序列长度即可,那么除了最长公共子序列之外的字符都是必须删除的,最后用两个字符串的总长度减去两个最长公共子序列的长度就是删除的最少步数。 + +代码如下: + +```CPP +class Solution { +public: + int minDistance(string word1, string word2) { + vector> dp(word1.size()+1, vector(word2.size()+1, 0)); + for (int i=1; i<=word1.size(); i++){ + for (int j=1; j<=word2.size(); j++){ + if (word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1; + else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); + } + } + return word1.size()+word2.size()-dp[word1.size()][word2.size()]*2; + } +}; + +``` + ## 其他语言版本 From 43eb0269d3dbbf47794eeee8690bcebae3d523db Mon Sep 17 00:00:00 2001 From: chenhaoran14 <2718827494@qq.com> Date: Thu, 20 Jan 2022 12:04:49 +0800 Subject: [PATCH 050/257] =?UTF-8?q?=E5=AF=B9Java=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=89=8D=E5=BA=8F=E6=8E=92=E5=88=97=E7=9A=84=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 45b576e7..4beed650 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -116,19 +116,19 @@ Java: ```Java // 前序遍历·递归·LC144_二叉树的前序遍历 class Solution { - ArrayList preOrderReverse(TreeNode root) { - ArrayList result = new ArrayList(); - preOrder(root, result); + public List preorderTraversal(TreeNode root) { + List result = new ArrayList(); + preorder(root, result); return result; } - void preOrder(TreeNode root, ArrayList result) { + public void preorder(TreeNode root, List result) { if (root == null) { return; } - result.add(root.val); // 注意这一句 - preOrder(root.left, result); - preOrder(root.right, result); + result.add(root.val); + preorder(root.left, result); + preorder(root.right, result); } } // 中序遍历·递归·LC94_二叉树的中序遍历 From e0c6492d6e141d8ff20a1bd2a2cc4d0337b88286 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 20 Jan 2022 14:56:16 +0800 Subject: [PATCH 051/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880028.?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0strStr.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0028.实现strStr.md | 77 +++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index f0b56719..5f1fa137 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -929,6 +929,83 @@ var strStr = function (haystack, needle) { }; ``` +TypeScript版本: + +> 前缀表统一减一 + +```typescript +function strStr(haystack: string, needle: string): number { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = -1; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j >= 0 && str[i] !== str[j + 1]) { + j = next[j]; + } + if (str[i] === str[j + 1]) { + j++; + } + next[i] = j; + } + return next; + } + if (needle.length === 0) return 0; + let next: number[] = getNext(needle); + let j: number = -1; + for (let i = 0, length = haystack.length; i < length; i++) { + while (j >= 0 && haystack[i] !== needle[j + 1]) { + j = next[j]; + } + if (haystack[i] === needle[j + 1]) { + if (j === needle.length - 2) { + return i - j - 1; + } + j++; + } + } + return -1; +}; +``` + +> 前缀表不减一 + +```typescript +// 不减一版本 +function strStr(haystack: string, needle: string): number { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = 0; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j > 0 && str[i] !== str[j]) { + j = next[j - 1]; + } + if (str[i] === str[j]) { + j++; + } + next[i] = j; + } + return next; + } + if (needle.length === 0) return 0; + let next: number[] = getNext(needle); + let j: number = 0; + for (let i = 0, length = haystack.length; i < length; i++) { + while (j > 0 && haystack[i] !== needle[j]) { + j = next[j - 1]; + } + if (haystack[i] === needle[j]) { + if (j === needle.length - 1) { + return i - j; + } + j++; + } + } + return -1; +} +``` + Swift 版本 > 前缀表统一减一 From 59c95ff24d60ec7809aa80c632b3728291892077 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Thu, 20 Jan 2022 08:29:02 +0000 Subject: [PATCH 052/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200343.=E6=95=B4?= =?UTF-8?q?=E6=95=B0=E6=8B=86=E5=88=86.md=20C=E8=AF=AD=E8=A8=80=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/0343.整数拆分.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 5d11f670..9882c6ea 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -271,5 +271,40 @@ var integerBreak = function(n) { }; ``` +C: +```c +//初始化DP数组 +int *initDP(int num) { + int* dp = (int*)malloc(sizeof(int) * (num + 1)); + int i; + for(i = 0; i < num + 1; ++i) { + dp[i] = 0; + } + return dp; +} + +//取三数最大值 +int max(int num1, int num2, int num3) { + int tempMax = num1 > num2 ? num1 : num2; + return tempMax > num3 ? tempMax : num3; +} + +int integerBreak(int n){ + int *dp = initDP(n); + //初始化dp[2]为1 + dp[2] = 1; + + int i; + for(i = 3; i <= n; ++i) { + int j; + for(j = 1; j < i - 1; ++j) { + //取得上次循环:dp[i],原数相乘,或j*dp[]i-j] 三数中的最大值 + dp[i] = max(dp[i], j * (i - j), j * dp[i - j]); + } + } + return dp[n]; +} +``` + -----------------------
From 7aba93c8e1bbb3f623c1f67f9f2d7f794aaefd78 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 20 Jan 2022 17:15:09 +0800 Subject: [PATCH 053/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880459.?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E7=9A=84=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?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/0459.重复的子字符串.md | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 9c74f4a7..ccfb485c 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -361,7 +361,65 @@ var repeatedSubstringPattern = function (s) { }; ``` +TypeScript: +> 前缀表统一减一 + +```typescript +function repeatedSubstringPattern(s: string): boolean { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = -1; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j >= 0 && str[i] !== str[j + 1]) { + j = next[j]; + } + if (str[i] === str[j + 1]) { + j++; + } + next[i] = j; + } + return next; + } + + let next: number[] = getNext(s); + let sLength: number = s.length; + let nextLength: number = next.length; + let suffixLength: number = next[nextLength - 1] + 1; + if (suffixLength > 0 && sLength % (sLength - suffixLength) === 0) return true; + return false; +}; +``` + +> 前缀表不减一 + +```typescript +function repeatedSubstringPattern(s: string): boolean { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = 0; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j > 0 && str[i] !== str[j]) { + j = next[j - 1]; + } + if (str[i] === str[j]) { + j++; + } + next[i] = j; + } + return next; + } + + let next: number[] = getNext(s); + let sLength: number = s.length; + let nextLength: number = next.length; + let suffixLength: number = next[nextLength - 1]; + if (suffixLength > 0 && sLength % (sLength - suffixLength) === 0) return true; + return false; +}; +``` -----------------------
From 0e75c5d92e619bffb60a63db4d606a492045b732 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, 20 Jan 2022 20:32:17 +0800 Subject: [PATCH 054/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20257.=20=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84?= =?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/0257.二叉树的所有路径.md | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index cb837d87..7b5fc2e9 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -581,7 +581,72 @@ var binaryTreePaths = function(root) { }; ``` +Swift: +> 递归/回溯 +```swift +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var path = [Int]() + _binaryTreePaths(root, path: &path, res: &res) + return res +} +func _binaryTreePaths(_ root: TreeNode, path: inout [Int], res: inout [String]) { + path.append(root.val) + if root.left == nil && root.right == nil { + var str = "" + for i in 0 ..< path.count - 1 { + str.append("\(path[i])->") + } + str.append("\(path.last!)") + res.append(str) + return + } + if let left = root.left { + _binaryTreePaths(left, path: &path, res: &res) + path.removeLast() + } + if let right = root.right { + _binaryTreePaths(right, path: &path, res: &res) + path.removeLast() + } +} +``` + +> 迭代 +```swift +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var stackNode = [TreeNode]() + stackNode.append(root) + + var stackStr = [String]() + stackStr.append("\(root.val)") + + while !stackNode.isEmpty { + let node = stackNode.popLast()! + let str = stackStr.popLast()! + if node.left == nil && node.right == nil { + res.append(str) + } + if let left = node.left { + stackNode.append(left) + stackStr.append("\(str)->\(left.val)") + } + if let right = node.right { + stackNode.append(right) + stackStr.append("\(str)->\(right.val)") + } + } + return res +} +``` -----------------------
From 02fd6b8f9a9dc49af1612762c80a439e0a1f5e04 Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Fri, 21 Jan 2022 10:45:10 +0800 Subject: [PATCH 055/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0257.=20=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=20Swift=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0257.二叉树的所有路径.md | 91 +++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index cb837d87..9ccd81d8 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -581,6 +581,97 @@ var binaryTreePaths = function(root) { }; ``` +Swift: + +递归法: + +```swift +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var result = Array() + var path = Array() + guard let root = root else { + return result + } + traversal(root, &path, &result) + return result + } + + func traversal(_ cur: TreeNode, _ path: inout Array, _ result: inout Array) { + path.append(cur.val) + // 递归终止条件:到达叶子节点 + if cur.left == nil && cur.right == nil { + var pathString = "" + // 处理 path 前面的元素 + for i in 0.. [String] { + // 保存树的遍历节点 + var treeStack = [TreeNode]() + // 保存遍历路径的节点 + var pathStack = [String]() + // 保存最终路径集合 + var result = [String]() + guard let root = root else { + return result + } + treeStack.append(root) + pathStack.append(String(root.val)) + while !treeStack.isEmpty { + let node = treeStack.removeLast() + let path = pathStack.removeLast() + + // 遇到叶子节点 + if node.left == nil && node.right == nil { + result.append(path) + } + + if let rightNode = node.right { + treeStack.append(rightNode) + let tmp = path + "->" + String(rightNode.val) + pathStack.append(tmp) + } + + if let leftNode = node.left { + treeStack.append(leftNode) + let tmp = path + "->" + String(leftNode.val) + pathStack.append(tmp) + } + } + + return result + } +``` + ----------------------- From d29fa29a87e8e5b2739f5033423cc6666d1ced42 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 21 Jan 2022 14:16:33 +0800 Subject: [PATCH 056/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880232.?= =?UTF-8?q?=E7=94=A8=E6=A0=88=E5=AE=9E=E7=8E=B0=E9=98=9F=E5=88=97.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 4edba2f2..33ce8114 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -348,7 +348,44 @@ MyQueue.prototype.empty = function() { }; ``` +TypeScript: + +```typescript +class MyQueue { + private stackIn: number[] + private stackOut: number[] + constructor() { + this.stackIn = []; + this.stackOut = []; + } + + push(x: number): void { + this.stackIn.push(x); + } + + pop(): number { + if (this.stackOut.length === 0) { + while (this.stackIn.length > 0) { + this.stackOut.push(this.stackIn.pop()!); + } + } + return this.stackOut.pop()!; + } + + peek(): number { + let temp: number = this.pop(); + this.stackOut.push(temp); + return temp; + } + + empty(): boolean { + return this.stackIn.length === 0 && this.stackOut.length === 0; + } +} +``` + Swift: + ```swift class MyQueue { From 1264fa87ac45c189ed9cc9caee88ef627c352e05 Mon Sep 17 00:00:00 2001 From: chengleqi Date: Fri, 21 Jan 2022 14:38:11 +0800 Subject: [PATCH 057/257] =?UTF-8?q?update=200063.=E4=B8=8D=E5=90=8C?= =?UTF-8?q?=E8=B7=AF=E5=BE=84II.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0063.不同路径II.md | 43 +++++++++++++------------------------ 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 6f405d6a..105b6402 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -266,46 +266,33 @@ Go: ```go func uniquePathsWithObstacles(obstacleGrid [][]int) int { - m,n:= len(obstacleGrid),len(obstacleGrid[0]) + m, n := len(obstacleGrid), len(obstacleGrid[0]) // 定义一个dp数组 - dp := make([][]int,m) - for i,_ := range dp { - dp[i] = make([]int,n) + dp := make([][]int, m) + for i, _ := range dp { + dp[i] = make([]int, n) } - // 初始化 - for i:=0;i Date: Fri, 21 Jan 2022 17:25:00 +0800 Subject: [PATCH 058/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880225.?= =?UTF-8?q?=E7=94=A8=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index fdb544a6..961fad38 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -598,7 +598,80 @@ MyStack.prototype.empty = function() { ``` +TypeScript: + +版本一:使用两个队列模拟栈 + +```typescript +class MyStack { + private queue: number[]; + private tempQueue: number[]; + constructor() { + this.queue = []; + this.tempQueue = []; + } + + push(x: number): void { + this.queue.push(x); + } + + pop(): number { + for (let i = 0, length = this.queue.length - 1; i < length; i++) { + this.tempQueue.push(this.queue.shift()!); + } + let res: number = this.queue.pop()!; + let temp: number[] = this.queue; + this.queue = this.tempQueue; + this.tempQueue = temp; + return res; + } + + top(): number { + let res: number = this.pop(); + this.push(res); + return res; + } + + empty(): boolean { + return this.queue.length === 0; + } +} +``` + +版本二:使用一个队列模拟栈 + +```typescript +class MyStack { + private queue: number[]; + constructor() { + this.queue = []; + } + + push(x: number): void { + this.queue.push(x); + } + + pop(): number { + for (let i = 0, length = this.queue.length - 1; i < length; i++) { + this.queue.push(this.queue.shift()!); + } + return this.queue.shift()!; + } + + top(): number { + let res: number = this.pop(); + this.push(res); + return res; + } + + empty(): boolean { + return this.queue.length === 0; + } +} +``` + Swift + ```Swift // 定义一个队列数据结构 class Queue { From f54af7ff39bb3c2d268eb1daff3bd2f5c8ca8b72 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 21 Jan 2022 20:57:58 +0800 Subject: [PATCH 059/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880020.?= =?UTF-8?q?=E6=9C=89=E6=95=88=E7=9A=84=E6=8B=AC=E5=8F=B7.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/0020.有效的括号.md | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 9e4046d4..95d62e42 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -283,8 +283,60 @@ var isValid = function(s) { }; ``` +TypeScript: + +版本一:普通版 + +```typescript +function isValid(s: string): boolean { + let helperStack: string[] = []; + for (let i = 0, length = s.length; i < length; i++) { + let x: string = s[i]; + switch (x) { + case '(': + helperStack.push(')'); + break; + case '[': + helperStack.push(']'); + break; + case '{': + helperStack.push('}'); + break; + default: + if (helperStack.pop() !== x) return false; + break; + } + } + return helperStack.length === 0; +}; +``` + +版本二:优化版 + +```typescript +function isValid(s: string): boolean { + type BracketMap = { + [index: string]: string; + } + let helperStack: string[] = []; + let bracketMap: BracketMap = { + '(': ')', + '[': ']', + '{': '}' + } + for (let i of s) { + if (bracketMap.hasOwnProperty(i)) { + helperStack.push(bracketMap[i]); + } else if (i !== helperStack.pop()) { + return false; + } + } + return helperStack.length === 0; +}; +``` Swift + ```swift func isValid(_ s: String) -> Bool { var stack = [String.Element]() From 61b0ddef35b07f7b459d9bfac774691bcf6cec98 Mon Sep 17 00:00:00 2001 From: coolcty Date: Fri, 21 Jan 2022 17:52:43 +0100 Subject: [PATCH 060/257] =?UTF-8?q?Update=200031.=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=8E=92=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0031.下一个排列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 84bf3e60..2219e24d 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -81,7 +81,7 @@ public: for (int j = nums.size() - 1; j > i; j--) { if (nums[j] > nums[i]) { swap(nums[j], nums[i]); - sort(nums.begin() + i + 1, nums.end()); + reverse(nums.begin() + i + 1, nums.end()); return; } } From 2ec4867125e60381b9ded470a59ad89d0b8401d1 Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Sat, 22 Jan 2022 10:26:18 +0800 Subject: [PATCH 061/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20404.=20=E5=B7=A6?= =?UTF-8?q?=E5=8F=B6=E5=AD=90=E4=B9=8B=E5=92=8C=20Swift=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/0404.左叶子之和.md | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index ddbd100e..09272052 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -373,6 +373,54 @@ var sumOfLeftLeaves = function(root) { ``` +## Swift + +**递归法** +```swift +func sumOfLeftLeaves(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + + let leftValue = sumOfLeftLeaves(root.left) + let rightValue = sumOfLeftLeaves(root.right) + + var midValue: Int = 0 + if root.left != nil && root.left?.left == nil && root.left?.right == nil { + midValue = root.left!.val + } + + let sum = midValue + leftValue + rightValue + return sum +} +``` +**迭代法** +```swift +func sumOfLeftLeaves(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + + var stack = Array() + stack.append(root) + var sum = 0 + + while !stack.isEmpty { + let lastNode = stack.removeLast() + + if lastNode.left != nil && lastNode.left?.left == nil && lastNode.left?.right == nil { + sum += lastNode.left!.val + } + if let right = lastNode.right { + stack.append(right) + } + if let left = lastNode.left { + stack.append(left) + } + } + return sum +} +``` From 26c7fd202afc2aac492c2db589a3c4af5af3fcf3 Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Sat, 22 Jan 2022 11:38:28 +0800 Subject: [PATCH 062/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20513.=20=E6=89=BE?= =?UTF-8?q?=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC=20Swift?= =?UTF-8?q?=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0513.找树左下角的值.md | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 99f42d34..84ed3932 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -433,6 +433,74 @@ var findBottomLeftValue = function(root) { }; ``` +## Swift + +递归版本: + +```swift +var maxLen = -1 +var maxLeftValue = 0 +func findBottomLeftValue_2(_ root: TreeNode?) -> Int { + traversal(root, 0) + return maxLeftValue +} + +func traversal(_ root: TreeNode?, _ deep: Int) { + guard let root = root else { + return + } + + if root.left == nil && root.right == nil { + if deep > maxLen { + maxLen = deep + maxLeftValue = root.val + } + return + } + + if root.left != nil { + traversal(root.left, deep + 1) + } + + if root.right != nil { + traversal(root.right, deep + 1) + } + return +} +``` +层序遍历: + +```swift +func findBottomLeftValue(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + + var queue = [root] + var result = 0 + + while !queue.isEmpty { + let size = queue.count + for i in 0.. Date: Sat, 22 Jan 2022 17:45:40 +0800 Subject: [PATCH 063/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881047.?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=AD=97=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E6=89=80=E6=9C=89=E7=9B=B8=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9?= =?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/1047.删除字符串中的所有相邻重复项.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index d6eefd07..9a0bb1c1 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -267,8 +267,32 @@ var removeDuplicates = function(s) { }; ``` +TypeScript: + +```typescript +function removeDuplicates(s: string): string { + const helperStack: string[] = []; + let i: number = 0; + while (i < s.length) { + let top: string = helperStack[helperStack.length - 1]; + if (top === s[i]) { + helperStack.pop(); + } else { + helperStack.push(s[i]); + } + i++; + } + let res: string = ''; + while (helperStack.length > 0) { + res = helperStack.pop() + res; + } + return res; +}; +``` + C: 方法一:使用栈 + ```c char * removeDuplicates(char * s){ //求出字符串长度 From 2b33b45170c22eb4b900bc85ff04ad5ce0a5c2e2 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Sat, 22 Jan 2022 10:39:07 +0000 Subject: [PATCH 064/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200096.=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?.md=20C=E8=AF=AD=E8=A8=80=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0096.不同的二叉搜索树.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index d4b8d024..d6f7aca7 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -227,7 +227,34 @@ const numTrees =(n) => { }; ``` +C: +```c +//开辟dp数组 +int *initDP(int n) { + int *dp = (int *)malloc(sizeof(int) * (n + 1)); + int i; + for(i = 0; i <= n; ++i) + dp[i] = 0; + return dp; +} +int numTrees(int n){ + //开辟dp数组 + int *dp = initDP(n); + //将dp[0]设为1 + dp[0] = 1; + + int i, j; + for(i = 1; i <= n; ++i) { + for(j = 1; j <= i; ++j) { + //递推公式:dp[i] = d[i] + 根为j时左子树种类个数 * 根为j时右子树种类个数 + dp[i] += dp[j - 1] * dp[i - j]; + } + } + + return dp[n]; +} +``` -----------------------
From 718e67acef29a7f21f7914d0b1e175b2b52a4063 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Sat, 22 Jan 2022 10:41:09 +0000 Subject: [PATCH 065/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=200096.=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E7=9A=84=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?.md=20C=E8=AF=AD=E8=A8=80=E8=A7=A3=E6=B3=95=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=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/0096.不同的二叉搜索树.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index d6f7aca7..d334a29c 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -247,7 +247,7 @@ int numTrees(int n){ int i, j; for(i = 1; i <= n; ++i) { for(j = 1; j <= i; ++j) { - //递推公式:dp[i] = d[i] + 根为j时左子树种类个数 * 根为j时右子树种类个数 + //递推公式:dp[i] = dp[i] + 根为j时左子树种类个数 * 根为j时右子树种类个数 dp[i] += dp[j - 1] * dp[i - j]; } } From 3fb923694db6cdd6a1b38f16cfcc294bfa415876 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 22 Jan 2022 22:20:24 +0800 Subject: [PATCH 066/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880150.?= =?UTF-8?q?=E9=80=86=E6=B3=A2=E5=85=B0=E8=A1=A8=E8=BE=BE=E5=BC=8F=E6=B1=82?= =?UTF-8?q?=E5=80=BC.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0150.逆波兰表达式求值.md | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index f44703f1..f4dad823 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -210,6 +210,71 @@ var evalRPN = function(tokens) { }; ``` +TypeScript: + +普通版: + +```typescript +function evalRPN(tokens: string[]): number { + let helperStack: number[] = []; + let temp: number; + let i: number = 0; + while (i < tokens.length) { + let t: string = tokens[i]; + switch (t) { + case '+': + temp = helperStack.pop()! + helperStack.pop()!; + helperStack.push(temp); + break; + case '-': + temp = helperStack.pop()!; + temp = helperStack.pop()! - temp; + helperStack.push(temp); + break; + case '*': + temp = helperStack.pop()! * helperStack.pop()!; + helperStack.push(temp); + break; + case '/': + temp = helperStack.pop()!; + temp = Math.trunc(helperStack.pop()! / temp); + helperStack.push(temp); + break; + default: + helperStack.push(Number(t)); + break; + } + i++; + } + return helperStack.pop()!; +}; +``` + +优化版: + +```typescript +function evalRPN(tokens: string[]): number { + const helperStack: number[] = []; + const operatorMap: Map number> = new Map([ + ['+', (a, b) => a + b], + ['-', (a, b) => a - b], + ['/', (a, b) => Math.trunc(a / b)], + ['*', (a, b) => a * b], + ]); + let a: number, b: number; + for (let t of tokens) { + if (operatorMap.has(t)) { + b = helperStack.pop()!; + a = helperStack.pop()!; + helperStack.push(operatorMap.get(t)!(a, b)); + } else { + helperStack.push(Number(t)); + } + } + return helperStack.pop()!; +}; +``` + python3 ```python From b5becb3291def44a5ddbccda6f6be7ae3266f634 Mon Sep 17 00:00:00 2001 From: chengleqi Date: Sun, 23 Jan 2022 17:23:36 +0800 Subject: [PATCH 067/257] =?UTF-8?q?bug-fix=200494.=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E5=92=8C.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0494.目标和.md | 43 +++-------------------------------------- 1 file changed, 3 insertions(+), 40 deletions(-) diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 1835f498..0faef4a5 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -289,7 +289,7 @@ func findTargetSumWays(nums []int, target int) int { for _, v := range nums { sum += v } - if target > sum { + if abs(target) > sum { return 0 } if (sum+target)%2 == 1 { @@ -311,49 +311,12 @@ func findTargetSumWays(nums []int, target int) int { } return dp[bag] } -``` -> 更新版,上一个跑不通了,因为会存在bag 小于0的情况 -```go -func findTargetSumWays(nums []int, target int) int { - //先转化为数学问题 - //a-b=target - //a+b=sum - //a=(target+sum)/2 - //求出sum - var sum int - for _,value:=range nums{ - sum+=value - } - //如果sum { From b3078ef51c321e386f5900e4f43c3b2c68dd0ca0 Mon Sep 17 00:00:00 2001 From: zhicheng lee <904688436@qq.com> Date: Sun, 23 Jan 2022 22:59:59 +0800 Subject: [PATCH 068/257] =?UTF-8?q?Update=200435.=E6=97=A0=E9=87=8D?= =?UTF-8?q?=E5=8F=A0=E5=8C=BA=E9=97=B4.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新Java版本代码 --- problems/0435.无重叠区间.md | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 118360bc..389443d1 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -183,28 +183,22 @@ public: ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { - if (intervals.length < 2) return 0; - - Arrays.sort(intervals, new Comparator() { - @Override - public int compare(int[] o1, int[] o2) { - if (o1[1] != o2[1]) { - return Integer.compare(o1[1],o2[1]); - } else { - return Integer.compare(o1[0],o2[0]); - } - } + Arrays.sort(intervals, (a, b) -> { + if (a[0] == a[0]) return a[1] - b[1]; + return a[0] - b[0]; }); - int count = 1; - int edge = intervals[0][1]; - for (int i = 1; i < intervals.length; i++) { - if (edge <= intervals[i][0]){ - count ++; //non overlap + 1 + int count = 0; + int edge = Integer.MIN_VALUE; + for (int i = 0; i < intervals.length; i++) { + if (edge <= intervals[i][0]) { edge = intervals[i][1]; + } else { + count++; } } - return intervals.length - count; + + return count; } } ``` From 00728847e17558cda0d76ff87e544b5a0a5e2dfb Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Mon, 24 Jan 2022 11:36:06 +0800 Subject: [PATCH 069/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200112.=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=80=BB=E5=92=8C=E3=80=810113.=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=80=BB=E5=92=8C=20II=20Swift=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 117 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 910e57c8..5ec8ffd0 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -766,7 +766,124 @@ let pathSum = function(root, targetSum) { }; ``` +## Swift +0112.路径总和 + +**递归** +```swift +func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { + guard let root = root else { + return false + } + + return traversal(root, targetSum - root.val) +} + +func traversal(_ cur: TreeNode?, _ count: Int) -> Bool { + if cur?.left == nil && cur?.right == nil && count == 0 { + return true + } + + if cur?.left == nil && cur?.right == nil { + return false + } + + if let leftNode = cur?.left { + if traversal(leftNode, count - leftNode.val) { + return true + } + } + + if let rightNode = cur?.right { + if traversal(rightNode, count - rightNode.val) { + return true + } + } + + return false +} +``` +**迭代** +```swift +func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { + guard let root = root else { + return false + } + + var stack = Array<(TreeNode, Int)>() + stack.append((root, root.val)) + + while !stack.isEmpty { + let node = stack.removeLast() + + if node.0.left == nil && node.0.right == nil && targetSum == node.1 { + return true + } + + if let rightNode = node.0.right { + stack.append((rightNode, node.1 + rightNode.val)) + } + + if let leftNode = node.0.left { + stack.append((leftNode, node.1 + leftNode.val)) + } + } + + return false +} +``` + +0113.路径总和 II + +**递归** + +```swift +var result = [[Int]]() +var path = [Int]() +func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] { + result.removeAll() + path.removeAll() + guard let root = root else { + return result + } + path.append(root.val) + traversal(root, count: targetSum - root.val) + return result + +} + +func traversal(_ cur: TreeNode?, count: Int) { + var count = count + // 遇到了叶子节点且找到了和为targetSum的路径 + if cur?.left == nil && cur?.right == nil && count == 0 { + result.append(path) + return + } + + // 遇到叶子节点而没有找到合适的边,直接返回 + if cur?.left == nil && cur?.right == nil{ + return + } + + if let leftNode = cur?.left { + path.append(leftNode.val) + count -= leftNode.val + traversal(leftNode, count: count)// 递归 + count += leftNode.val// 回溯 + path.removeLast()// 回溯 + } + + if let rightNode = cur?.right { + path.append(rightNode.val) + count -= rightNode.val + traversal(rightNode, count: count)// 递归 + count += rightNode.val// 回溯 + path.removeLast()// 回溯 + } + return +} +``` From ac9f8c612033d87221e1fc79ce093211a1f5570b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 15:51:26 +0800 Subject: [PATCH 070/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880239.?= =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC?= =?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/0239.滑动窗口最大值.md | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index d9788f63..6e8039f4 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -418,7 +418,56 @@ var maxSlidingWindow = function (nums, k) { }; ``` +TypeScript: + +```typescript +function maxSlidingWindow(nums: number[], k: number): number[] { + /** 单调递减队列 */ + class MonoQueue { + private queue: number[]; + constructor() { + this.queue = []; + }; + /** 入队:value如果大于队尾元素,则将队尾元素删除,直至队尾元素大于value,或者队列为空 */ + public enqueue(value: number): void { + let back: number | undefined = this.queue[this.queue.length - 1]; + while (back !== undefined && back < value) { + this.queue.pop(); + back = this.queue[this.queue.length - 1]; + } + this.queue.push(value); + }; + /** 出队:只有当队头元素等于value,才出队 */ + public dequeue(value: number): void { + let top: number | undefined = this.top(); + if (top !== undefined && top === value) { + this.queue.shift(); + } + } + public top(): number | undefined { + return this.queue[0]; + } + } + const helperQueue: MonoQueue = new MonoQueue(); + let i: number = 0, + j: number = 0; + let resArr: number[] = []; + while (j < k) { + helperQueue.enqueue(nums[j++]); + } + resArr.push(helperQueue.top()!); + while (j < nums.length) { + helperQueue.enqueue(nums[j]); + helperQueue.dequeue(nums[i]); + resArr.push(helperQueue.top()!); + j++, i++; + } + return resArr; +}; +``` + Swift: + ```Swift /// 双向链表 class DoublyListNode { From a12ad31f46c082f35a88441d65ef322740d12520 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 16:03:36 +0800 Subject: [PATCH 071/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=880239.?= =?UTF-8?q?=E6=BB=91=E5=8A=A8=E7=AA=97=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC?= =?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E8=A7=84=E8=8C=83=E5=8C=96js=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/0239.滑动窗口最大值.md | 57 +++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 6e8039f4..adf3548c 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -395,26 +395,49 @@ func maxSlidingWindow(nums []int, k int) []int { Javascript: ```javascript +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ var maxSlidingWindow = function (nums, k) { - // 队列数组(存放的是元素下标,为了取值方便) - const q = []; - // 结果数组 - const ans = []; - for (let i = 0; i < nums.length; i++) { - // 若队列不为空,且当前元素大于等于队尾所存下标的元素,则弹出队尾 - while (q.length && nums[i] >= nums[q[q.length - 1]]) { - q.pop(); + class MonoQueue { + queue; + constructor() { + this.queue = []; + } + enqueue(value) { + let back = this.queue[this.queue.length - 1]; + while (back !== undefined && back < value) { + this.queue.pop(); + back = this.queue[this.queue.length - 1]; + } + this.queue.push(value); + } + dequeue(value) { + let front = this.front(); + if (front === value) { + this.queue.shift(); + } + } + front() { + return this.queue[0]; + } } - // 入队当前元素下标 - q.push(i); - // 判断当前最大值(即队首元素)是否在窗口中,若不在便将其出队 - if (q[0] <= i - k) { - q.shift(); + let helperQueue = new MonoQueue(); + let i = 0, j = 0; + let resArr = []; + while (j < k) { + helperQueue.enqueue(nums[j++]); } - // 当达到窗口大小时便开始向结果中添加数据 - if (i >= k - 1) ans.push(nums[q[0]]); - } - return ans; + resArr.push(helperQueue.front()); + while (j < nums.length) { + helperQueue.enqueue(nums[j]); + helperQueue.dequeue(nums[i]); + resArr.push(helperQueue.front()); + i++, j++; + } + return resArr; }; ``` From 9272063cf2627a6334cea807cd3de2e7166da1af Mon Sep 17 00:00:00 2001 From: YDLIN <1924723909@qq.com> Date: Mon, 24 Jan 2022 16:42:47 +0800 Subject: [PATCH 072/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200654.=20=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E4=BA=8C=E5=8F=89=E6=A0=91=20Swift=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/0654.最大二叉树.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index b4679c7d..44c74f89 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -401,6 +401,33 @@ struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize){ } ``` +## Swift +```swift +func constructMaximumBinaryTree(_ nums: inout [Int]) -> TreeNode? { + return traversal(&nums, 0, nums.count) +} + +func traversal(_ nums: inout [Int], _ left: Int, _ right: Int) -> TreeNode? { + if left >= right { + return nil + } + + var maxValueIndex = left + for i in (left + 1).. nums[maxValueIndex] { + maxValueIndex = i + } + } + + let root = TreeNode(nums[maxValueIndex]) + + root.left = traversal(&nums, left, maxValueIndex) + root.right = traversal(&nums, maxValueIndex + 1, right) + return root +} +``` + + -----------------------
From fee948b2af53b7bfc583fbbe5c43cd98c04e462f Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Mon, 24 Jan 2022 08:57:02 +0000 Subject: [PATCH 073/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200005.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index f204a607..588afc22 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -462,7 +462,56 @@ var longestPalindrome = function(s) { }; ``` +## C +动态规划: +```c +//初始化dp数组,全部初始为false +bool **initDP(int strLen) { + bool **dp = (bool **)malloc(sizeof(bool *) * strLen); + int i, j; + for(i = 0; i < strLen; ++i) { + dp[i] = (bool *)malloc(sizeof(bool) * strLen); + for(j = 0; j < strLen; ++j) + dp[i][j] = false; + } + return dp; +} +char * longestPalindrome(char * s){ + //求出字符串长度 + int strLen = strlen(s); + //初始化dp数组,元素初始化为false + bool **dp = initDP(strLen); + int maxLength = 0, left = 0, right = 0; + + //从下到上,从左到右遍历 + int i, j; + for(i = strLen - 1; i >= 0; --i) { + for(j = i; j < strLen; ++j) { + //若当前i与j所指字符一样 + if(s[i] == s[j]) { + //若i、j指向相邻字符或同一字符,则为回文字符串 + if(j - i <= 1) + dp[i][j] = true; + //若i+1与j-1所指字符串为回文字符串,则i、j所指字符串为回文字符串 + else if(dp[i + 1][j - 1]) + dp[i][j] = true; + } + //若新的字符串的长度大于之前的最大长度,进行更新 + if(dp[i][j] && j - i + 1 > maxLength) { + maxLength = j - i + 1; + left = i; + right = j; + } + } + } + //复制回文字符串,并返回 + char *ret = (char*)malloc(sizeof(char) * (maxLength + 1)); + memcpy(ret, s + left, maxLength); + ret[maxLength] = 0; + return ret; +} +``` -----------------------
From 60c3a27ce9537d7361e4927b21129bf77be507ba Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 17:39:34 +0800 Subject: [PATCH 074/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880347.?= =?UTF-8?q?=E5=89=8DK=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 8bd774e9..1d6a358b 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -358,6 +358,22 @@ PriorityQueue.prototype.compare = function(index1, index2) { } ``` +TypeScript: + +```typescript +function topKFrequent(nums: number[], k: number): number[] { + const countMap: Map = new Map(); + for (let num of nums) { + countMap.set(num, (countMap.get(num) || 0) + 1); + } + // tS没有最小堆的数据结构,所以直接对整个数组进行排序,取前k个元素 + return [...countMap.entries()] + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map(i => i[0]); +}; +``` + ----------------------- From de37c44f4fbc6b368f1afe6a51e508c949ff9271 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 19:41:17 +0800 Subject: [PATCH 075/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index cc899850..009e8276 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -227,7 +227,23 @@ function TreeNode(val, left, right) { } ``` +TypeScript: + +```typescript +class TreeNode { + public val: number; + public left: TreeNode | null; + public right: TreeNode | null; + constructor(val?: number, left?: TreeNode, right?: TreeNode) { + this.val = val === undefined ? 0 : val; + this.left = left === undefined ? null : left; + this.right = right === undefined ? null : right; + } +} +``` + Swift: + ```Swift class TreeNode { var value: T From a488a3414a8c0e3408678f8393b116837e6240ea Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 20:25:45 +0800 Subject: [PATCH 076/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86?= =?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/二叉树的递归遍历.md | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 4beed650..ba13fc74 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -358,7 +358,51 @@ var postorderTraversal = function(root) { }; ``` +TypeScript: + +```typescript +// 前序遍历 +function preorderTraversal(node: TreeNode | null): number[] { + function traverse(node: TreeNode | null, res: number[]): void { + if (node === null) return; + res.push(node.val); + traverse(node.left, res); + traverse(node.right, res); + } + const res: number[] = []; + traverse(node, res); + return res; +} + +// 中序遍历 +function inorderTraversal(node: TreeNode | null): number[] { + function traverse(node: TreeNode | null, res: number[]): void { + if (node === null) return; + traverse(node.left, res); + res.push(node.val); + traverse(node.right, res); + } + const res: number[] = []; + traverse(node, res); + return res; +} + +// 后序遍历 +function postorderTraversal(node: TreeNode | null): number[] { + function traverse(node: TreeNode | null, res: number[]): void { + if (node === null) return; + traverse(node.left, res); + traverse(node.right, res); + res.push(node.val); + } + const res: number[] = []; + traverse(node, res); + return res; +} +``` + C: + ```c //前序遍历: void preOrderTraversal(struct TreeNode* root, int* ret, int* returnSize) { From fec8e0882a771ea5866e0611c01874d6850654e6 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 20:27:15 +0800 Subject: [PATCH 077/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86?= =?UTF-8?q?.md=EF=BC=89=EF=BC=9A=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84js=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 34 ---------------------------------- 1 file changed, 34 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index ba13fc74..c481fd11 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -270,40 +270,6 @@ func postorderTraversal(root *TreeNode) (res []int) { } ``` -javaScript: - -```js - -前序遍历: - -var preorderTraversal = function(root, res = []) { - if (!root) return res; - res.push(root.val); - preorderTraversal(root.left, res) - preorderTraversal(root.right, res) - return res; -}; - -中序遍历: - -var inorderTraversal = function(root, res = []) { - if (!root) return res; - inorderTraversal(root.left, res); - res.push(root.val); - inorderTraversal(root.right, res); - return res; -}; - -后序遍历: - -var postorderTraversal = function(root, res = []) { - if (!root) return res; - postorderTraversal(root.left, res); - postorderTraversal(root.right, res); - res.push(root.val); - return res; -}; -``` Javascript版本: 前序遍历: From 1efb77e96310d884eb2b8647232dd1586f4f0afb Mon Sep 17 00:00:00 2001 From: zucong Date: Tue, 25 Jan 2022 14:33:12 +0800 Subject: [PATCH 078/257] =?UTF-8?q?=E4=BC=98=E5=8C=96=200112.=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=80=BB=E5=92=8C=20Go=E7=89=88=E6=9C=AC=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/0112.路径总和.md | 101 ++++++++++++++++---------------------- 1 file changed, 41 insertions(+), 60 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 910e57c8..b3e121ba 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -531,82 +531,63 @@ class solution: ```go //递归法 /** - * definition for a binary tree node. - * type treenode struct { - * val int - * left *treenode - * right *treenode + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -func haspathsum(root *treenode, targetsum int) bool { - var flage bool //找没找到的标志 - if root==nil{ - return flage +func hasPathSum(root *TreeNode, targetSum int) bool { + if root == nil { + return false } - pathsum(root,0,targetsum,&flage) - return flage -} -func pathsum(root *treenode, sum int,targetsum int,flage *bool){ - sum+=root.val - if root.left==nil&&root.right==nil&&sum==targetsum{ - *flage=true - return - } - if root.left!=nil&&!(*flage){//左节点不为空且还没找到 - pathsum(root.left,sum,targetsum,flage) - } - if root.right!=nil&&!(*flage){//右节点不为空且没找到 - pathsum(root.right,sum,targetsum,flage) + + targetSum -= root.Val // 将targetSum在遍历每层的时候都减去本层节点的值 + if root.Left == nil && root.Right == nil && targetSum == 0 { // 如果剩余的targetSum为0, 则正好就是符合的结果 + return true } + return hasPathSum(root.Left, targetSum) || hasPathSum(root.Right, targetSum) // 否则递归找 } ``` -113 递归法 +113. 路径总和 II ```go /** - * definition for a binary tree node. - * type treenode struct { - * val int - * left *treenode - * right *treenode + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -func pathsum(root *treenode, targetsum int) [][]int { - var result [][]int//最终结果 - if root==nil{ - return result - } - var sumnodes []int//经过路径的节点集合 - haspathsum(root,&sumnodes,targetsum,&result) +func pathSum(root *TreeNode, targetSum int) [][]int { + result := make([][]int, 0) + traverse(root, &result, new([]int), targetSum) return result } -func haspathsum(root *treenode,sumnodes *[]int,targetsum int,result *[][]int){ - *sumnodes=append(*sumnodes,root.val) - if root.left==nil&&root.right==nil{//叶子节点 - fmt.println(*sumnodes) - var sum int - var number int - for k,v:=range *sumnodes{//求该路径节点的和 - sum+=v - number=k - } - tempnodes:=make([]int,number+1)//新的nodes接受指针里的值,防止最终指针里的值发生变动,导致最后的结果都是最后一个sumnodes的值 - for k,v:=range *sumnodes{ - tempnodes[k]=v - } - if sum==targetsum{ - *result=append(*result,tempnodes) - } + +func traverse(node *TreeNode, result *[][]int, currPath *[]int, targetSum int) { + if node == nil { // 这个判空也可以挪到递归遍历左右子树时去判断 + return } - if root.left!=nil{ - haspathsum(root.left,sumnodes,targetsum,result) - *sumnodes=(*sumnodes)[:len(*sumnodes)-1]//回溯 - } - if root.right!=nil{ - haspathsum(root.right,sumnodes,targetsum,result) - *sumnodes=(*sumnodes)[:len(*sumnodes)-1]//回溯 + + targetSum -= node.Val // 将targetSum在遍历每层的时候都减去本层节点的值 + *currPath = append(*currPath, node.Val) // 把当前节点放到路径记录里 + + if node.Left == nil && node.Right == nil && targetSum == 0 { // 如果剩余的targetSum为0, 则正好就是符合的结果 + // 不能直接将currPath放到result里面, 因为currPath是共享的, 每次遍历子树时都会被修改 + pathCopy := make([]int, len(*currPath)) + for i, element := range *currPath { + pathCopy[i] = element + } + *result = append(*result, pathCopy) // 将副本放到结果集里 } + + traverse(node.Left, result, currPath, targetSum) + traverse(node.Right, result, currPath, targetSum) + *currPath = (*currPath)[:len(*currPath)-1] // 当前节点遍历完成, 从路径记录里删除掉 } ``` From 3a46ffdad4cfcc2bc3695db93f4760b9ae70b4d2 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Tue, 25 Jan 2022 12:54:50 +0000 Subject: [PATCH 079/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200005.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E5=8F=8C=E6=8C=87=E9=92=88=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 588afc22..99458825 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -513,5 +513,41 @@ char * longestPalindrome(char * s){ } ``` +双指针: +```c +int left, maxLength; +void extend(char *str, int i, int j, int size) { + while(i >= 0 && j < size && str[i] == str[j]) { + //若当前子字符串长度大于最长的字符串长度,进行更新 + if(j - i + 1 > maxLength) { + maxLength = j - i + 1; + left = i; + } + //左指针左移,右指针右移。扩大搜索范围 + ++j, --i; + } +} + +char * longestPalindrome(char * s){ + left = right = maxLength = 0; + int size = strlen(s); + + int i; + for(i = 0; i < size; ++i) { + //长度为单数的子字符串 + extend(s, i, i, size); + //长度为双数的子字符串 + extend(s, i, i + 1, size); + } + + //复制子字符串 + char *subStr = (char *)malloc(sizeof(char) * (maxLength + 1)); + memcpy(subStr, s + left, maxLength); + subStr[maxLength] = 0; + + return subStr; +} +``` + -----------------------
From d40a15eccca9212f701c4602a514168ab52fecf6 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 26 Jan 2022 10:40:30 +0800 Subject: [PATCH 080/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86?= =?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/二叉树的迭代遍历.md | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 4cb94cb5..ba38726b 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -454,6 +454,61 @@ var postorderTraversal = function(root, res = []) { }; ``` +TypeScript: + +```typescript +// 前序遍历(迭代法) +function preorderTraversal(root: TreeNode | null): number[] { + if (root === null) return []; + let res: number[] = []; + let helperStack: TreeNode[] = []; + let curNode: TreeNode = root; + helperStack.push(curNode); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + res.push(curNode.val); + if (curNode.right !== null) helperStack.push(curNode.right); + if (curNode.left !== null) helperStack.push(curNode.left); + } + return res; +}; + +// 中序遍历(迭代法) +function inorderTraversal(root: TreeNode | null): number[] { + let helperStack: TreeNode[] = []; + let res: number[] = []; + if (root === null) return res; + let curNode: TreeNode | null = root; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + res.push(curNode.val); + curNode = curNode.right; + } + } + return res; +}; + +// 后序遍历(迭代法) +function postorderTraversal(root: TreeNode | null): number[] { + let helperStack: TreeNode[] = []; + let res: number[] = []; + let curNode: TreeNode; + if (root === null) return res; + helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + res.push(curNode.val); + if (curNode.left !== null) helperStack.push(curNode.left); + if (curNode.right !== null) helperStack.push(curNode.right); + } + return res.reverse(); +}; +``` + Swift: > 迭代法前序遍历 From 9d09b11d56722748e00d3647cdcd228793baaa66 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Wed, 26 Jan 2022 09:26:03 +0000 Subject: [PATCH 081/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200143.=E9=87=8D?= =?UTF-8?q?=E6=8E=92=E9=93=BE=E8=A1=A8.md=20C=E8=AF=AD=E8=A8=80=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/0143.重排链表.md | 68 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 4ea9cb97..00622623 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -439,7 +439,75 @@ var reorderList = function(head, s = [], tmp) { } ``` +### C +方法三:反转链表 +```c +//翻转链表 +struct ListNode *reverseList(struct ListNode *head) { + if(!head) + return NULL; + struct ListNode *preNode = NULL, *curNode = head; + while(curNode) { + //创建tempNode记录curNode->next(即将被更新) + struct ListNode* tempNode = curNode->next; + //将curNode->next指向preNode + curNode->next = preNode; + //更新preNode为curNode + preNode = curNode; + //curNode更新为原链表中下一个元素 + curNode = tempNode; + } + return preNode; +} +void reorderList(struct ListNode* head){ + //slow用来截取到链表的中间节点(第一个链表的最后节点),每次循环跳一个节点。fast用来辅助,每次循环跳两个节点 + struct ListNode *fast = head, *slow = head; + while(fast && fast->next && fast->next->next) { + //fast每次跳两个节点 + fast = fast->next->next; + //slow每次跳一个节点 + slow = slow->next; + } + //将slow->next后的节点翻转 + struct ListNode *sndLst = reverseList(slow->next); + //将第一个链表与第二个链表断开 + slow->next = NULL; + //因为插入从curNode->next开始,curNode刚开始已经head。所以fstList要从head->next开始 + struct ListNode *fstLst = head->next; + struct ListNode *curNode = head; + + int count = 0; + //当第一个链表和第二个链表中都有节点时循环 + while(sndLst && fstLst) { + //count为奇数,插入fstLst中的节点 + if(count % 2) { + curNode->next = fstLst; + fstLst = fstLst->next; + } + //count为偶数,插入sndList的节点 + else { + curNode->next = sndLst; + sndLst = sndLst->next; + } + //设置下一个节点 + curNode = curNode->next; + //更新count + ++count; + } + + //若两个链表fstList和sndLst中还有节点,将其放入链表 + if(fstLst) { + curNode->next = fstLst; + } + if(sndLst) { + curNode->next = sndLst; + } + + //返回链表 + return head; +} +``` ----------------------- From 7ed2a3aef7b10b48fe7f8127f185f4a6efc9952c Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 26 Jan 2022 19:18:23 +0800 Subject: [PATCH 082/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E7=BB=9F=E4=B8=80=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E6=B3=95.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的统一迭代法.md | 68 ++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index 2ff84817..f6edf586 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -522,7 +522,75 @@ var postorderTraversal = function(root, res = []) { ``` +TypeScript: +```typescript +// 前序遍历(迭代法) +function preorderTraversal(root: TreeNode | null): number[] { + let helperStack: (TreeNode | null)[] = []; + let res: number[] = []; + let curNode: TreeNode | null; + if (root === null) return res; + helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + if (curNode !== null) { + if (curNode.right !== null) helperStack.push(curNode.right); + helperStack.push(curNode); + helperStack.push(null); + if (curNode.left !== null) helperStack.push(curNode.left); + } else { + curNode = helperStack.pop()!; + res.push(curNode.val); + } + } + return res; +}; + +// 中序遍历(迭代法) +function inorderTraversal(root: TreeNode | null): number[] { + let helperStack: (TreeNode | null)[] = []; + let res: number[] = []; + let curNode: TreeNode | null; + if (root === null) return res; + helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + if (curNode !== null) { + if (curNode.right !== null) helperStack.push(curNode.right); + helperStack.push(curNode); + helperStack.push(null); + if (curNode.left !== null) helperStack.push(curNode.left); + } else { + curNode = helperStack.pop()!; + res.push(curNode.val); + } + } + return res; +}; + +// 后序遍历(迭代法) +function postorderTraversal(root: TreeNode | null): number[] { + let helperStack: (TreeNode | null)[] = []; + let res: number[] = []; + let curNode: TreeNode | null; + if (root === null) return res; + helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + if (curNode !== null) { + if (curNode.right !== null) helperStack.push(curNode.right); + helperStack.push(curNode); + helperStack.push(null); + if (curNode.left !== null) helperStack.push(curNode.left); + } else { + curNode = helperStack.pop()!; + res.push(curNode.val); + } + } + return res; +}; +``` -----------------------
From 878231551829fdd9deea2f2457eb09b794d7ed65 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 26 Jan 2022 21:20:36 +0800 Subject: [PATCH 083/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880102.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86.md=20&=20107.=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=B1=82=E6=AC=A1=E9=81=8D=E5=8E=86=20II=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1fb9b633..b108c8f0 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -246,7 +246,35 @@ var levelOrder = function(root) { ``` +TypeScript: + +```typescript +function levelOrder(root: TreeNode | null): number[][] { + let helperQueue: TreeNode[] = []; + let res: number[][] = []; + let tempArr: number[] = []; + if (root !== null) helperQueue.push(root); + let curNode: TreeNode; + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + curNode = helperQueue.shift()!; + tempArr.push(curNode.val); + if (curNode.left !== null) { + helperQueue.push(curNode.left); + } + if (curNode.right !== null) { + helperQueue.push(curNode.right); + } + } + res.push(tempArr); + tempArr = []; + } + return res; +}; +``` + Swift: + ```swift func levelOrder(_ root: TreeNode?) -> [[Int]] { var res = [[Int]]() @@ -454,7 +482,31 @@ var levelOrderBottom = function(root) { }; ``` +TypeScript: + +```typescript +function levelOrderBottom(root: TreeNode | null): number[][] { + let helperQueue: TreeNode[] = []; + let resArr: number[][] = []; + let tempArr: number[] = []; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + tempArr.push(tempNode.val); + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + resArr.push(tempArr); + tempArr = []; + } + return resArr.reverse(); +}; +``` + Swift: + ```swift func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { var res = [[Int]]() From bb02fb957bfef34ffc7270e70b4cf41b829ed3a6 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Wed, 26 Jan 2022 23:13:07 +0000 Subject: [PATCH 084/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200052.N=E7=9A=87?= =?UTF-8?q?=E5=90=8EII.md=20C=E8=AF=AD=E8=A8=80=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0052.N皇后II.md | 60 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/problems/0052.N皇后II.md b/problems/0052.N皇后II.md index 78531798..67e439ca 100644 --- a/problems/0052.N皇后II.md +++ b/problems/0052.N皇后II.md @@ -143,5 +143,65 @@ var totalNQueens = function(n) { return count; }; ``` + +C +```c +//path[i]为在i行,path[i]列上存在皇后 +int *path; +int pathTop; +int answer; +//检查当前level行index列放置皇后是否合法 +int isValid(int index, int level) { + int i; + //updater为若斜角存在皇后,其所应在的列 + //用来检查左上45度是否存在皇后 + int lCornerUpdater = index - level; + //用来检查右上135度是否存在皇后 + int rCornerUpdater = index + level; + for(i = 0; i < pathTop; ++i) { + //path[i] == index检查index列是否存在皇后 + //检查斜角皇后:只要path[i] == updater,就说明当前位置不可放置皇后。 + //path[i] == lCornerUpdater检查左上角45度是否有皇后 + //path[i] == rCornerUpdater检查右上角135度是否有皇后 + if(path[i] == index || path[i] == lCornerUpdater || path[i] == rCornerUpdater) + return 0; + //更新updater指向下一行对应的位置 + ++lCornerUpdater; + --rCornerUpdater; + } + return 1; +} + +//回溯算法:level为当前皇后行数 +void backTracking(int n, int level) { + //若path中元素个数已经为n,则证明有一种解法。answer+1 + if(pathTop == n) { + ++answer; + return; + } + + int i; + for(i = 0; i < n; ++i) { + //若当前level行,i列是合法的放置位置。就将i放入path中 + if(isValid(i, level)) { + path[pathTop++] = i; + backTracking(n, level + 1); + //回溯 + --pathTop; + } + } +} + +int totalNQueens(int n){ + answer = 0; + pathTop = 0; + path = (int *)malloc(sizeof(int) * n); + + backTracking(n, 0); + + return answer; +} +``` + -----------------------
From 023ec6900a759e030712edf5362b65569935df75 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Thu, 27 Jan 2022 13:43:43 +0000 Subject: [PATCH 085/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200129.=E6=B1=82?= =?UTF-8?q?=E6=A0=B9=E5=88=B0=E5=8F=B6=E5=AD=90=E8=8A=82=E7=82=B9=E6=95=B0?= =?UTF-8?q?=E5=AD=97=E4=B9=8B=E5=92=8C.md=20C=E8=AF=AD=E8=A8=80=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/0129.求根到叶子节点数字之和.md | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index d07d5244..980779c2 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -289,7 +289,33 @@ var sumNumbers = function(root) { }; ``` +C: +```c +//sum记录总和 +int sum; +void traverse(struct TreeNode *node, int val) { + //更新val为根节点到当前节点的和 + val = val * 10 + node->val; + //若当前节点为叶子节点,记录val + if(!node->left && !node->right) { + sum+=val; + return; + } + //若有左/右节点,遍历左/右节点 + if(node->left) + traverse(node->left, val); + if(node->right) + traverse(node->right, val); +} +int sumNumbers(struct TreeNode* root){ + sum = 0; + + traverse(root, 0); + + return sum; +} +``` -----------------------
From 7fe4ea3fbc3d93665e2ed5663a1c41c6f21d5874 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Thu, 27 Jan 2022 19:32:30 +0000 Subject: [PATCH 086/257] =?UTF-8?q?Add=200209.=E9=95=BF=E5=BA=A6=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E7=9A=84=E5=AD=90=E6=95=B0=E7=BB=84.md=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0209.长度最小的子数组.md | 50 +++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index 17422ca0..dc1d9f18 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -330,5 +330,55 @@ def min_sub_array_len(target, nums) end ``` +C: +暴力解法: +```c +int minSubArrayLen(int target, int* nums, int numsSize){ + //初始化最小长度为INT_MAX + int minLength = INT_MAX; + int sum; + + int left, right; + for(left = 0; left < numsSize; ++left) { + //每次遍历都清零sum,计算当前位置后和>=target的子数组的长度 + sum = 0; + //从left开始,sum中添加元素 + for(right = left; right < numsSize; ++right) { + sum += nums[right]; + //若加入当前元素后,和大于target,则更新minLength + if(sum >= target) { + int subLength = right - left + 1; + minLength = minLength < subLength ? minLength : subLength; + } + } + } + //若minLength不为INT_MAX,则返回minLnegth + return minLength == INT_MAX ? 0 : minLength; +} +``` + +滑动窗口: +```c +int minSubArrayLen(int target, int* nums, int numsSize){ + //初始化最小长度为INT_MAX + int minLength = INT_MAX; + int sum = 0; + + int left = 0, right = 0; + //右边界向右扩展 + for(; right < numsSize; ++right) { + sum += nums[right]; + //当sum的值大于等于target时,保存长度,并且收缩左边界 + while(sum >= target) { + int subLength = right - left + 1; + minLength = minLength < subLength ? minLength : subLength; + sum -= nums[left++]; + } + } + //若minLength不为INT_MAX,则返回minLnegth + return minLength == INT_MAX ? 0 : minLength; +} +``` + -----------------------
From e177bca526cd33ff4dce70b188f2214598941b0e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 27 Jan 2022 22:35:30 +0800 Subject: [PATCH 087/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88199.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=8F=B3=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index b108c8f0..18e19227 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -709,7 +709,28 @@ var rightSideView = function(root) { }; ``` +TypeScript: + +```typescript +function rightSideView(root: TreeNode | null): number[] { + let helperQueue: TreeNode[] = []; + let resArr: number[] = []; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (i === length - 1) resArr.push(tempNode.val); + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resArr; +}; +``` + Swift: + ```swift func rightSideView(_ root: TreeNode?) -> [Int] { var res = [Int]() From daf710bde6eb82f2c5b2a87254ca9860d79af80e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 11:32:57 +0800 Subject: [PATCH 088/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88637.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82=E5=B9=B3=E5=9D=87?= =?UTF-8?q?=E5=80=BC=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 18e19227..9ff4f2e9 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -941,7 +941,32 @@ var averageOfLevels = function(root) { }; ``` +TypeScript: + +```typescript +function averageOfLevels(root: TreeNode | null): number[] { + let helperQueue: TreeNode[] = []; + let resArr: number[] = []; + let total: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + let length = helperQueue.length; + for (let i = 0; i < length; i++) { + tempNode = helperQueue.shift()!; + total += tempNode.val; + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + resArr.push(total / length); + total = 0; + } + return resArr; +}; +``` + Swift: + ```swift func averageOfLevels(_ root: TreeNode?) -> [Double] { var res = [Double]() From 2862d47368512a9cbc7e7184775d99d8e53f72df Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 11:44:49 +0800 Subject: [PATCH 089/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88429.N?= =?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?=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/0102.二叉树的层序遍历.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 9ff4f2e9..5dd448b7 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1190,7 +1190,30 @@ var levelOrder = function(root) { }; ``` +TypeScript: + +```typescript +function levelOrder(root: Node | null): number[][] { + let helperQueue: Node[] = []; + let resArr: number[][] = []; + let tempArr: number[] = []; + if (root !== null) helperQueue.push(root); + let curNode: Node; + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + curNode = helperQueue.shift()!; + tempArr.push(curNode.val); + helperQueue.push(...curNode.children); + } + resArr.push(tempArr); + tempArr = []; + } + return resArr; +}; +``` + Swift: + ```swift func levelOrder(_ root: Node?) -> [[Int]] { var res = [[Int]]() From 9329ecff5e95e5bc1e8cb17fbba1135765fd3286 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 12:02:15 +0800 Subject: [PATCH 090/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88515.?= =?UTF-8?q?=E5=9C=A8=E6=AF=8F=E4=B8=AA=E6=A0=91=E8=A1=8C=E4=B8=AD=E6=89=BE?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E5=80=BC=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 5dd448b7..6f90cb75 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1393,7 +1393,34 @@ var largestValues = function(root) { }; ``` +TypeScript: + +```typescript +function largestValues(root: TreeNode | null): number[] { + let helperQueue: TreeNode[] = []; + let resArr: number[] = []; + let tempNode: TreeNode; + let max: number = 0; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (i === 0) { + max = tempNode.val; + } else { + max = max > tempNode.val ? max : tempNode.val; + } + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + resArr.push(max); + } + return resArr; +}; +``` + Swift: + ```swift func largestValues(_ root: TreeNode?) -> [Int] { var res = [Int]() From 992cd6d7f3bc2b0065bf8f3f3ff064a13c66dde3 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 16:10:56 +0800 Subject: [PATCH 091/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88116.?= =?UTF-8?q?=E5=A1=AB=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84?= =?UTF-8?q?=E4=B8=8B=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E6=8C=87=E9=92=88=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescrip?= =?UTF-8?q?t=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 6f90cb75..12f96469 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1611,6 +1611,31 @@ var connect = function(root) { }; ``` +TypeScript: + +```typescript +function connect(root: Node | null): Node | null { + let helperQueue: Node[] = []; + let preNode: Node, curNode: Node; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + if (i === 0) { + preNode = helperQueue.shift()!; + } else { + curNode = helperQueue.shift()!; + preNode.next = curNode; + preNode = curNode; + } + if (preNode.left) helperQueue.push(preNode.left); + if (preNode.right) helperQueue.push(preNode.right); + } + preNode.next = null; + } + return root; +}; +``` + go: ```GO From d1abb0cbb4397a950479788497e3ec21adbcea22 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 16:21:25 +0800 Subject: [PATCH 092/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88117.?= =?UTF-8?q?=E5=A1=AB=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84?= =?UTF-8?q?=E4=B8=8B=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9?= =?UTF-8?q?=E6=8C=87=E9=92=88II=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescr?= =?UTF-8?q?ipt=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 12f96469..a7716d92 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1862,6 +1862,31 @@ var connect = function(root) { return root; }; ``` +TypeScript: + +```typescript +function connect(root: Node | null): Node | null { + let helperQueue: Node[] = []; + let preNode: Node, curNode: Node; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + if (i === 0) { + preNode = helperQueue.shift()!; + } else { + curNode = helperQueue.shift()!; + preNode.next = curNode; + preNode = curNode; + } + if (preNode.left) helperQueue.push(preNode.left); + if (preNode.right) helperQueue.push(preNode.right); + } + preNode.next = null; + } + return root; +}; +``` + go: ```GO From bdb0954e32976832b9bd99dd2dcb2744d55e665b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 17:11:11 +0800 Subject: [PATCH 093/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88104.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index a7716d92..9ac23fdf 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2131,7 +2131,28 @@ var maxDepth = function(root) { }; ``` +TypeScript: + +```typescript +function maxDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resDepth: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resDepth++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + } + return resDepth; +}; +``` + Swift: + ```swift func maxDepth(_ root: TreeNode?) -> Int { guard let root = root else { From 626db3fc67ba0a478f39331c4788bca15314a720 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 28 Jan 2022 20:33:04 +0800 Subject: [PATCH 094/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88111.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 9ac23fdf..1a92d42f 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -2349,7 +2349,29 @@ var minDepth = function(root) { }; ``` +TypeScript: + +```typescript +function minDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resMin: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resMin++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left === null && tempNode.right === null) return resMin; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resMin; +}; +``` + Swift: + ```swift func minDepth(_ root: TreeNode?) -> Int { guard let root = root else { From 653d645dabd54c9b2d94afc27dc3cb308f82b519 Mon Sep 17 00:00:00 2001 From: Younglesszzz <571688981@qq.com> Date: Sat, 29 Jan 2022 13:29:28 +0800 Subject: [PATCH 095/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=BA=8C?= =?UTF-8?q?=E7=BB=B4=E6=95=B0=E7=BB=84=E7=89=88=E6=9C=AC=EF=BC=8C=E7=9B=B8?= =?UTF-8?q?=E6=AF=94=E4=BA=8E=E4=B8=80=E7=BB=B4=E5=A5=BD=E7=90=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1049.最后一块石头的重量II.md | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index d64e7e56..7b67b1ac 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -153,6 +153,8 @@ public: Java: + +一维数组版本 ```Java class Solution { public int lastStoneWeightII(int[] stones) { @@ -173,6 +175,41 @@ class Solution { return sum - 2 * dp[target]; } } +``` +二维数组版本(便于理解) +```Java +class Solution { + public int lastStoneWeightII(int[] stones) { + int sum = 0; + for (int s : stones) { + sum += s; + } + + int target = sum / 2; + //初始化,dp[i][j]为可以放0-i物品,背包容量为j的情况下背包中的最大价值 + int[][] dp = new int[stones.length][target + 1]; + //dp[i][0]默认初始化为0 + //dp[0][j]取决于stones[0] + for (int j = stones[0]; j <= target; j++) { + dp[0][j] = stones[0]; + } + + for (int i = 1; i < stones.length; i++) { + for (int j = 1; j <= target; j++) {//注意是等于 + if (j >= stones[i]) { + //不放:dp[i - 1][j] 放:dp[i - 1][j - stones[i]] + stones[i] + dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - stones[i]] + stones[i]); + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + + System.out.println(dp[stones.length - 1][target]); + return (sum - dp[stones.length - 1][target]) - dp[stones.length - 1][target]; + } +} + ``` Python: From b1c3d5c4f9db71676ebc44f9c41a10778dfea1c5 Mon Sep 17 00:00:00 2001 From: Younglesszzz <571688981@qq.com> Date: Sat, 29 Jan 2022 13:39:27 +0800 Subject: [PATCH 096/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=BA=8C?= =?UTF-8?q?=E7=BB=B4=E6=95=B0=E7=BB=84=E7=89=88=E6=9C=AC=EF=BC=8C=E7=9B=B8?= =?UTF-8?q?=E6=AF=94=E4=BA=8E=E4=B8=80=E7=BB=B4=E5=A5=BD=E7=90=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0416.分割等和子集.md | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 45b8b416..9da1f8d5 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -210,6 +210,45 @@ class Solution { } ``` +二维数组版本(易于理解): +```Java +class Solution { + public boolean canPartition(int[] nums) { + int sum = 0; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + } + + if (sum % 2 == 1) + return false; + int target = sum / 2; + + //dp[i][j]代表可装物品为0-i,背包容量为j的情况下,背包内容量的最大价值 + int[][] dp = new int[nums.length][target + 1]; + + //初始化,dp[0][j]的最大价值nums[0](if j > weight[i]) + //dp[i][0]均为0,不用初始化 + for (int j = nums[0]; j <= target; j++) { + dp[0][j] = nums[0]; + } + + //遍历物品,遍历背包 + //递推公式: + for (int i = 1; i < nums.length; i++) { + for (int j = 0; j <= target; j++) { + //背包容量可以容纳nums[i] + if (j >= nums[i]) { + dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i]] + nums[i]); + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + + return dp[nums.length - 1][target] == target; + } +} +``` Python: ```python class Solution: From be3f2cfc8a6e0abc3fbbefb3d7d2967b686e96e2 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 29 Jan 2022 22:12:49 +0800 Subject: [PATCH 097/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880226.?= =?UTF-8?q?=E7=BF=BB=E8=BD=AC=E4=BA=8C=E5=8F=89=E6=A0=91.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/0226.翻转二叉树.md | 128 ++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index e6dbb709..8108e7ad 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -563,7 +563,135 @@ var invertTree = function(root) { }; ``` +### TypeScript: + +递归法: + +```typescript +// 递归法(前序遍历) +function invertTree(root: TreeNode | null): TreeNode | null { + if (root === null) return root; + let tempNode: TreeNode | null = root.left; + root.left = root.right; + root.right = tempNode; + invertTree(root.left); + invertTree(root.right); + return root; +}; + +// 递归法(后序遍历) +function invertTree(root: TreeNode | null): TreeNode | null { + if (root === null) return root; + invertTree(root.left); + invertTree(root.right); + let tempNode: TreeNode | null = root.left; + root.left = root.right; + root.right = tempNode; + return root; +}; + +// 递归法(中序遍历) +function invertTree(root: TreeNode | null): TreeNode | null { + if (root === null) return root; + invertTree(root.left); + let tempNode: TreeNode | null = root.left; + root.left = root.right; + root.right = tempNode; + // 因为左右节点已经进行交换,此时的root.left 是原先的root.right + invertTree(root.left); + return root; +}; +``` + +迭代法: + +```typescript +// 迭代法(栈模拟前序遍历) +function invertTree(root: TreeNode | null): TreeNode | null { + let helperStack: TreeNode[] = []; + let curNode: TreeNode, + tempNode: TreeNode | null; + if (root !== null) helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + // 入栈操作最好在交换节点之前进行,便于理解 + if (curNode.right) helperStack.push(curNode.right); + if (curNode.left) helperStack.push(curNode.left); + tempNode = curNode.left; + curNode.left = curNode.right; + curNode.right = tempNode; + } + return root; +}; + +// 迭代法(栈模拟中序遍历-统一写法形式) +function invertTree(root: TreeNode | null): TreeNode | null { + let helperStack: (TreeNode | null)[] = []; + let curNode: TreeNode | null, + tempNode: TreeNode | null; + if (root !== null) helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop(); + if (curNode !== null) { + if (curNode.right !== null) helperStack.push(curNode.right); + helperStack.push(curNode); + helperStack.push(null); + if (curNode.left !== null) helperStack.push(curNode.left); + } else { + curNode = helperStack.pop()!; + tempNode = curNode.left; + curNode.left = curNode.right; + curNode.right = tempNode; + } + } + return root; +}; + +// 迭代法(栈模拟后序遍历-统一写法形式) +function invertTree(root: TreeNode | null): TreeNode | null { + let helperStack: (TreeNode | null)[] = []; + let curNode: TreeNode | null, + tempNode: TreeNode | null; + if (root !== null) helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop(); + if (curNode !== null) { + helperStack.push(curNode); + helperStack.push(null); + if (curNode.right !== null) helperStack.push(curNode.right); + if (curNode.left !== null) helperStack.push(curNode.left); + } else { + curNode = helperStack.pop()!; + tempNode = curNode.left; + curNode.left = curNode.right; + curNode.right = tempNode; + } + } + return root; +}; + +// 迭代法(队列模拟层序遍历) +function invertTree(root: TreeNode | null): TreeNode | null { + const helperQueue: TreeNode[] = []; + let curNode: TreeNode, + tempNode: TreeNode | null; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + curNode = helperQueue.shift()!; + tempNode = curNode.left; + curNode.left = curNode.right; + curNode.right = tempNode; + if (curNode.left !== null) helperQueue.push(curNode.left); + if (curNode.right !== null) helperQueue.push(curNode.right); + } + } + return root; +}; +``` + ### C: + 递归法 ```c struct TreeNode* invertTree(struct TreeNode* root){ From cee8536fa671b635f74edb1f7d296a5f2efc1bde Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 30 Jan 2022 13:17:47 +0800 Subject: [PATCH 098/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880101.?= =?UTF-8?q?=E5=AF=B9=E7=A7=B0=E4=BA=8C=E5=8F=89=E6=A0=91.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/0101.对称二叉树.md | 69 +++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 69bc41d3..e4e232c8 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -574,6 +574,75 @@ var isSymmetric = function(root) { }; ``` +## TypeScript: + +> 递归法 + +```typescript +function isSymmetric(root: TreeNode | null): boolean { + function recur(node1: TreeNode | null, node2: TreeNode | null): boolean { + if (node1 === null && node2 === null) return true; + if (node1 === null || node2 === null) return false; + if (node1.val !== node2.val) return false + let isSym1: boolean = recur(node1.left, node2.right); + let isSym2: boolean = recur(node1.right, node2.left); + return isSym1 && isSym2 + } + if (root === null) return true; + return recur(root.left, root.right); +}; +``` + +> 迭代法 + +```typescript +// 迭代法(队列) +function isSymmetric(root: TreeNode | null): boolean { + let helperQueue: (TreeNode | null)[] = []; + let tempNode1: TreeNode | null, + tempNode2: TreeNode | null; + if (root !== null) { + helperQueue.push(root.left); + helperQueue.push(root.right); + } + while (helperQueue.length > 0) { + tempNode1 = helperQueue.shift()!; + tempNode2 = helperQueue.shift()!; + if (tempNode1 === null && tempNode2 === null) continue; + if (tempNode1 === null || tempNode2 === null) return false; + if (tempNode1.val !== tempNode2.val) return false; + helperQueue.push(tempNode1.left); + helperQueue.push(tempNode2.right); + helperQueue.push(tempNode1.right); + helperQueue.push(tempNode2.left); + } + return true; +} + +// 迭代法(栈) +function isSymmetric(root: TreeNode | null): boolean { + let helperStack: (TreeNode | null)[] = []; + let tempNode1: TreeNode | null, + tempNode2: TreeNode | null; + if (root !== null) { + helperStack.push(root.left); + helperStack.push(root.right); + } + while (helperStack.length > 0) { + tempNode1 = helperStack.pop()!; + tempNode2 = helperStack.pop()!; + if (tempNode1 === null && tempNode2 === null) continue; + if (tempNode1 === null || tempNode2 === null) return false; + if (tempNode1.val !== tempNode2.val) return false; + helperStack.push(tempNode1.left); + helperStack.push(tempNode2.right); + helperStack.push(tempNode1.right); + helperStack.push(tempNode2.left); + } + return true; +}; +``` + ## Swift: > 递归 From 067f71cdf03858645ba70c5151a1d26f16d91928 Mon Sep 17 00:00:00 2001 From: zhicheng lee <904688436@qq.com> Date: Mon, 31 Jan 2022 11:54:59 +0800 Subject: [PATCH 099/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E8=83=8C=E5=8C=85.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加注释,去掉一个不必要的if语句 --- problems/背包问题理论基础完全背包.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index f79310b8..cea69c72 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -183,11 +183,9 @@ private static void testCompletePack(){ int[] value = {15, 20, 30}; int bagWeight = 4; int[] dp = new int[bagWeight + 1]; - for (int i = 0; i < weight.length; i++){ - for (int j = 1; j <= bagWeight; j++){ - if (j - weight[i] >= 0){ - dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); - } + for (int i = 0; i < weight.length; i++){ // 遍历物品 + for (int j = weight[i]; j <= bagWeight; j++){ // 遍历背包容量 + dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); } } for (int maxValue : dp){ @@ -201,8 +199,8 @@ private static void testCompletePackAnotherWay(){ int[] value = {15, 20, 30}; int bagWeight = 4; int[] dp = new int[bagWeight + 1]; - for (int i = 1; i <= bagWeight; i++){ - for (int j = 0; j < weight.length; j++){ + for (int i = 1; i <= bagWeight; i++){ // 遍历背包容量 + for (int j = 0; j < weight.length; j++){ // 遍历物品 if (i - weight[j] >= 0){ dp[i] = Math.max(dp[i], dp[i - weight[j]] + value[j]); } From 46571a3b9c619ac39c93becab1c1325fe211b545 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 31 Jan 2022 14:51:28 +0800 Subject: [PATCH 100/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880104.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=A4=A7=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 7038598b..6875ec74 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -598,7 +598,55 @@ var maxDepth = function(root) { }; ``` +## TypeScript: + +> 二叉树的最大深度: + +```typescript +// 后续遍历(自下而上) +function maxDepth(root: TreeNode | null): number { + if (root === null) return 0; + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; +}; + +// 前序遍历(自上而下) +function maxDepth(root: TreeNode | null): number { + function recur(node: TreeNode | null, count: number) { + if (node === null) { + resMax = resMax > count ? resMax : count; + return; + } + recur(node.left, count + 1); + recur(node.right, count + 1); + } + let resMax: number = 0; + let count: number = 0; + recur(root, count); + return resMax; +}; + +// 层序遍历(迭代法) +function maxDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resDepth: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resDepth++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + } + return resDepth; +}; +``` + + + ## C + 二叉树最大深度递归 ```c int maxDepth(struct TreeNode* root){ From 463f142f05d5759c8dfaa5f17dbebfa9ddf580f5 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 31 Jan 2022 16:07:01 +0800 Subject: [PATCH 101/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88559.n?= =?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?=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/0104.二叉树的最大深度.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 6875ec74..3eecdc92 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -643,7 +643,33 @@ function maxDepth(root: TreeNode | null): number { }; ``` +> N叉树的最大深度 +```typescript +// 后续遍历(自下而上) +function maxDepth(root: TreeNode | null): number { + if (root === null) return 0; + return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; +}; + +// 前序遍历(自上而下) +function maxDepth(root: TreeNode | null): number { + function recur(node: TreeNode | null, count: number) { + if (node === null) { + resMax = resMax > count ? resMax : count; + return; + } + recur(node.left, count + 1); + recur(node.right, count + 1); + } + let resMax: number = 0; + let count: number = 0; + recur(root, count); + return resMax; +}; + + +``` ## C From e4f674c61e71a7b33ec97e22acc6b7a44e075b6e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 1 Feb 2022 20:04:51 +0800 Subject: [PATCH 102/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880111.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E5=B0=8F=E6=B7=B1?= =?UTF-8?q?=E5=BA=A6.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0111.二叉树的最小深度.md | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index a439322a..224caa5e 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -404,6 +404,44 @@ var minDepth = function(root) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function minDepth(root: TreeNode | null): number { + if (root === null) return 0; + if (root.left !== null && root.right === null) { + return 1 + minDepth(root.left); + } + if (root.left === null && root.right !== null) { + return 1 + minDepth(root.right); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); +} +``` + +> 迭代法 + +```typescript +function minDepth(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resMin: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + resMin++; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left === null && tempNode.right === null) return resMin; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resMin; +}; +``` + ## Swift > 递归 From 8ac7cdce22a6f350ec57627e474bd482f5d041b3 Mon Sep 17 00:00:00 2001 From: hutbzc <3260189532@qq.com> Date: Tue, 1 Feb 2022 23:01:36 +0800 Subject: [PATCH 103/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880045.?= =?UTF-8?q?=E8=B7=B3=E8=B7=83=E6=B8=B8=E6=88=8FII.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E8=A1=A5=E5=85=85Java=E7=89=88=E6=9C=AC2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index a39c064a..7a3f048c 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -142,6 +142,7 @@ public: ### Java ```Java +// 版本一 class Solution { public int jump(int[] nums) { if (nums == null || nums.length == 0 || nums.length == 1) { @@ -172,7 +173,30 @@ class Solution { } ``` +```java +// 版本二 +class Solution { + public int jump(int[] nums) { + int result = 0; + // 当前覆盖的最远距离下标 + int end = 0; + // 下一步覆盖的最远距离下标 + int temp = 0; + for (int i = 0; i <= end && end < nums.length - 1; ++i) { + temp = Math.max(temp, i + nums[i]); + // 可达位置的改变次数就是跳跃次数 + if (i == end) { + end = temp; + result++; + } + } + return result; + } +} +``` + ### Python + ```python class Solution: def jump(self, nums: List[int]) -> int: From 40c06155f9e65e3525100ac6aff6f3ce6aeb8dac Mon Sep 17 00:00:00 2001 From: hutbzc <3260189532@qq.com> Date: Tue, 1 Feb 2022 23:04:07 +0800 Subject: [PATCH 104/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880139.?= =?UTF-8?q?=E5=8D=95=E8=AF=8D=E6=8B=86=E5=88=86.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Java=E5=9B=9E=E5=9B=9E=E6=BA=AF+=E8=AE=B0?= =?UTF-8?q?=E5=BF=86=E5=8C=96=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0139.单词拆分.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index e24ffc1a..1653a81a 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -248,6 +248,36 @@ class Solution { return valid[s.length()]; } } + +// 回溯法+记忆化 +class Solution { + public boolean wordBreak(String s, List wordDict) { + Set wordDictSet = new HashSet(wordDict); + int[] memory = new int[s.length()]; + return backTrack(s, wordDictSet, 0, memory); + } + + public boolean backTrack(String s, Set wordDictSet, int startIndex, int[] memory) { + // 结束条件 + if (startIndex >= s.length()) { + return true; + } + if (memory[startIndex] != 0) { + // 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能 + return memory[startIndex] == 1 ? true : false; + } + for (int i = startIndex; i < s.length(); ++i) { + // 处理 递归 回溯 循环不变量:[startIndex, i + 1) + String word = s.substring(startIndex, i + 1); + if (wordDictSet.contains(word) && backTrack(s, wordDictSet, i + 1, memory)) { + memory[startIndex] = 1; + return true; + } + } + memory[startIndex] = -1; + return false; + } +} ``` Python: From 5a2ff02b94d417a7a51d44998e212913afeba48b Mon Sep 17 00:00:00 2001 From: hutbzc <3260189532@qq.com> Date: Tue, 1 Feb 2022 23:08:56 +0800 Subject: [PATCH 105/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=880376.?= =?UTF-8?q?=E6=91=86=E5=8A=A8=E5=BA=8F=E5=88=97.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E9=80=BB=E8=BE=91=E5=B0=8F=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0376.摆动序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 2bc23182..d75311eb 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -174,7 +174,7 @@ public: ```Java class Solution { public int wiggleMaxLength(int[] nums) { - if (nums == null || nums.length <= 1) { + if (nums.length <= 1) { return nums.length; } //当前差值 From 2f1c56e6dd34a5a8ae89a8401219a0ce2dd623f3 Mon Sep 17 00:00:00 2001 From: Xiaofei-fei Date: Wed, 2 Feb 2022 18:47:01 +0800 Subject: [PATCH 106/257] =?UTF-8?q?494=E9=A2=98python=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .DS_Store | Bin 0 -> 8196 bytes problems/0494.目标和.md | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7794435bd6714aed6095604325ab6ffe84221748 GIT binary patch literal 8196 zcmeHMU2GIp6u#fIv@>*|1GG|b$8K6szzU`1r~D<`KM+bOc3ZkFVA<^sbYMDDcV^o{ zC8_Z*g7~0DeNjN;ix1VP7!wtvi3asattOIaj7FnRKFACD;<m0CQ8r?%*`* zup!Jqn1L_@VFtnsgc#mK>qC@oE@Ocl6VhKgsPK;f zB>54*zv!9H0lrT(kg-6H3F*61pW^g@z!kv}1Hzs3QEpB$7RWIng*$_AX9z|{a6*AU zI{8I?bB36ZVHsv1%)s;vaQet>kY$*|QrDl~QTewYB!ubsmP_3Yqqra9{olWg+mlT+n{GUw!6>BxFmbE zVwVEl+2`1MGX~dp^*L5{z;=7J1${}YFKZ<|qu#RO<_Uw^irv19V_AD0*W}%FCp=@s z+c#eT{C4F9d>fSP!^y{nJ6w>vh?lONbu4&8|RHg%m zmHORkhfBfBT2dIUR;$&HV*~|7b45$7x?bVg$!AiU;v1PT@4p;3+(h7x5C#;XGc$n|KQs@D4u2 zC47d@@il(J&-ewu;tyQKU-(*}`EPl8aOHV4$};qPPqUrg~a?_**LUMB<#)$$zerqZ#K$YPAhoU&S> zu&z*-$r>?ej;P+Hu9USFMJo{1s>o{MrL0MQRb3mYRkWn6<%w!lWTPT$5S7j9R?b5$ zUsQE9rYIWoE0M-XGv|^f6Uxsu`LjI>%9Uv=l#lj1Ssi`Gb+E&<$vniKWM>KOAFzw; zOLm$4$bMs22=4`ibPeTLfog0(4BN2-yU>DG>_Zp2(L-oAaM(xuF?h&gm{5NL591L$ zhR5*)p2jnH7SG`$w)*YO6S|2@2qi-i7<@G-u?1it6^4^W#!bE~N5N?f6* zX=ombXKc%{kB~0smvguYWuAEFGJgJVp8fa#n=rEQmBS2#8ThXmKz>uase!C#ThsVi zJ4*K literal 0 HcmV?d00001 diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 0faef4a5..f190b734 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -272,7 +272,8 @@ Python: class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: sumValue = sum(nums) - if target > sumValue or (sumValue + target) % 2 == 1: return 0 + #注意边界条件为 target>sumValue or target<-sumValue or (sumValue + target) % 2 == 1 + if abs(target) > sumValue or (sumValue + target) % 2 == 1: return 0 bagSize = (sumValue + target) // 2 dp = [0] * (bagSize + 1) dp[0] = 1 From 38c8b6849f32b47d59fc9ed5d1b394dda745b277 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 3 Feb 2022 20:03:43 +0800 Subject: [PATCH 107/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880222.?= =?UTF-8?q?=E5=AE=8C=E5=85=A8=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9=E4=B8=AA=E6=95=B0.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/0222.完全二叉树的节点个数.md | 60 ++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index 8d38bace..ffbc32ff 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -447,7 +447,63 @@ var countNodes = function(root) { }; ``` +## TypeScrpt: + +> 递归法 + +```typescript +function countNodes(root: TreeNode | null): number { + if (root === null) return 0; + return 1 + countNodes(root.left) + countNodes(root.right); +}; +``` + +> 迭代法 + +```typescript +function countNodes(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + let resCount: number = 0; + let tempNode: TreeNode; + if (root !== null) helperQueue.push(root); + while (helperQueue.length > 0) { + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + resCount++; + if (tempNode.left) helperQueue.push(tempNode.left); + if (tempNode.right) helperQueue.push(tempNode.right); + } + } + return resCount; +}; +``` + +> 利用完全二叉树性质 + +```typescript +function countNodes(root: TreeNode | null): number { + if (root === null) return 0; + let left: number = 0, + right: number = 0; + let curNode: TreeNode | null= root; + while (curNode !== null) { + left++; + curNode = curNode.left; + } + curNode = root; + while (curNode !== null) { + right++; + curNode = curNode.right; + } + if (left === right) { + return 2 ** left - 1; + } + return 1 + countNodes(root.left) + countNodes(root.right); +}; +``` + ## C: + 递归法 ```c int countNodes(struct TreeNode* root) { @@ -538,7 +594,7 @@ func _countNodes(_ root: TreeNode?) -> Int { return 1 + leftCount + rightCount } ``` - + > 层序遍历 ```Swift func countNodes(_ root: TreeNode?) -> Int { @@ -564,7 +620,7 @@ func countNodes(_ root: TreeNode?) -> Int { return res } ``` - + > 利用完全二叉树性质 ```Swift func countNodes(_ root: TreeNode?) -> Int { From ea5a011d783073dc0f98bd5d0a0130c97a02153c Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 5 Feb 2022 13:04:38 +0800 Subject: [PATCH 108/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880110.?= =?UTF-8?q?=E5=B9=B3=E8=A1=A1=E4=BA=8C=E5=8F=89=E6=A0=91.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/0110.平衡二叉树.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 9d43407a..8a701bb3 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -627,7 +627,26 @@ var isBalanced = function(root) { }; ``` +## TypeScript + +```typescript +// 递归法 +function isBalanced(root: TreeNode | null): boolean { + function getDepth(root: TreeNode | null): number { + if (root === null) return 0; + let leftDepth: number = getDepth(root.left); + if (leftDepth === -1) return -1; + let rightDepth: number = getDepth(root.right); + if (rightDepth === -1) return -1; + if (Math.abs(leftDepth - rightDepth) > 1) return -1; + return 1 + Math.max(leftDepth, rightDepth); + } + return getDepth(root) !== -1; +}; +``` + ## C + 递归法: ```c int getDepth(struct TreeNode* node) { From f9e5bce7d7b8b53d266ba082036677b30d092696 Mon Sep 17 00:00:00 2001 From: jobinben <1021137079@qq.com> Date: Sun, 6 Feb 2022 18:36:14 +0800 Subject: [PATCH 109/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=9802.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md=20JavaSc?= =?UTF-8?q?ript=E8=AF=AD=E8=A8=80=E8=A7=A3=E6=B3=95=E7=9A=84=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index dd91f069..2e7226de 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -224,12 +224,14 @@ var getIntersectionNode = function(headA, headB) { lenA = getListLen(headA), lenB = getListLen(headB); if(lenA < lenB) { + // 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 + // 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA] [curA, curB] = [curB, curA]; [lenA, lenB] = [lenB, lenA]; } let i = lenA - lenB; while(i-- > 0) { - curA = curA.next + curA = curA.next; } while(curA && curA !== curB) { curA = curA.next; From 343ddb37f9e84284ff8df34f89bed18522244e43 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 20:13:42 +0800 Subject: [PATCH 110/257] =?UTF-8?q?1047.=E5=88=A0=E9=99=A4=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E4=B8=AD=E7=9A=84=E6=89=80=E6=9C=89=E7=9B=B8?= =?UTF-8?q?=E9=82=BB=E9=87=8D=E5=A4=8D=E9=A1=B9=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?Swift=E7=89=88=E6=9C=AC=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1047.删除字符串中的所有相邻重复项.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index d6eefd07..9309aed8 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -322,14 +322,12 @@ char * removeDuplicates(char * s){ Swift: ```swift func removeDuplicates(_ s: String) -> String { - let array = Array(s) var stack = [Character]() - for c in array { - let last: Character? = stack.last - if stack.isEmpty || last != c { - stack.append(c) - } else { + for c in s { + if stack.last == c { stack.removeLast() + } else { + stack.append(c) } } return String(stack) From 2aa31ce54bcb186376a1341d8ef91282a8db4c6f Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 21:42:07 +0800 Subject: [PATCH 111/257] =?UTF-8?q?0239.=E6=BB=91=E5=8A=A8=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85Swift=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0239.滑动窗口最大值.md | 36 ++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index d9788f63..d7a94b5a 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -45,7 +45,7 @@ 这个队列应该长这个样子: -``` +```cpp class MyQueue { public: void pop(int value) { @@ -525,5 +525,39 @@ class Solution { } ``` +Swift解法二: + +```swift +func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] { + var result = [Int]() + var window = [Int]() + var right = 0, left = right - k + 1 + + while right < nums.count { + let value = nums[right] + + // 因为窗口移动丢弃的左边数 + if left > 0, left - 1 == window.first { + window.removeFirst() + } + + // 保证末尾的是最大的 + while !window.isEmpty, value > nums[window.last!] { + window.removeLast() + } + window.append(right) + + if left >= 0 { // 窗口形成 + result.append(nums[window.first!]) + } + + right += 1 + left += 1 + } + + return result +} +``` + -----------------------
From 40dc0d5e65fc36833c9d3fc77bba45606e83f739 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 20 Dec 2021 21:48:45 +0800 Subject: [PATCH 112/257] =?UTF-8?q?=E6=A0=88=E4=B8=8E=E9=98=9F=E5=88=97?= =?UTF-8?q?=E6=80=BB=E7=BB=93=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/栈与队列总结.md | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/problems/栈与队列总结.md b/problems/栈与队列总结.md index 8ec96a29..15093ca7 100644 --- a/problems/栈与队列总结.md +++ b/problems/栈与队列总结.md @@ -158,22 +158,5 @@ cd a/b/c/../../ 好了,栈与队列我们就总结到这里了,接下来Carl就要带大家开启新的篇章了,大家加油! - - - -## 其他语言版本 - - -Java: - - -Python: - - -Go: - - - - -----------------------
From c88aee12e53a301ede5ed3fa81023d98c1ce009b Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 11:29:56 +0800 Subject: [PATCH 113/257] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=80=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92?= =?UTF-8?q?=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树理论基础.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index cc899850..c5dd118b 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -154,7 +154,7 @@ C++代码如下: -``` +```cpp struct TreeNode { int val; TreeNode *left; @@ -163,7 +163,7 @@ struct TreeNode { }; ``` -大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子. +大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子。 这里要提醒大家要注意二叉树节点定义的书写方式。 @@ -177,7 +177,7 @@ struct TreeNode { 本篇我们介绍了二叉树的种类、存储方式、遍历方式以及定义,比较全面的介绍了二叉树各个方面的重点,帮助大家扫一遍基础。 -**说道二叉树,就不得不说递归,很多同学对递归都是又熟悉又陌生,递归的代码一般很简短,但每次都是一看就会,一写就废。** +**说到二叉树,就不得不说递归,很多同学对递归都是又熟悉又陌生,递归的代码一般很简短,但每次都是一看就会,一写就废。** ## 其他语言版本 From be6c45c636556b1c0d3838f265fe7830ca4f00ff Mon Sep 17 00:00:00 2001 From: jobinben <1021137079@qq.com> Date: Sun, 6 Feb 2022 19:06:51 +0800 Subject: [PATCH 114/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200110.=E5=B9=B3?= =?UTF-8?q?=E8=A1=A1=E4=BA=8C=E5=8F=89=E6=A0=91.md=20JavaScript=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=E6=9C=AC=E7=9A=84=E8=BF=AD=E4=BB=A3=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/0110.平衡二叉树.md | 45 ++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 9d43407a..8a11c013 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -604,7 +604,8 @@ func abs(a int)int{ } ``` -## JavaScript +## JavaScript +递归法: ```javascript var isBalanced = function(root) { //还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1 @@ -627,6 +628,48 @@ var isBalanced = function(root) { }; ``` +迭代法: +```javascript +// 获取当前节点的高度 +var getHeight = function (curNode) { + let queue = []; + if (curNode !== null) queue.push(curNode); // 压入当前元素 + let depth = 0, res = 0; + while (queue.length) { + let node = queue[queue.length - 1]; // 取出栈顶 + if (node !== null) { + queue.pop(); + queue.push(node); // 中 + queue.push(null); + depth++; + node.right && queue.push(node.right); // 右 + node.left && queue.push(node.left); // 左 + } else { + queue.pop(); + node = queue[queue.length - 1]; + queue.pop(); + depth--; + } + res = res > depth ? res : depth; + } + return res; +} +var isBalanced = function (root) { + if (root === null) return true; + let queue = [root]; + while (queue.length) { + let node = queue[queue.length - 1]; // 取出栈顶 + queue.pop(); + if (Math.abs(getHeight(node.left) - getHeight(node.right)) > 1) { + return false; + } + node.right && queue.push(node.right); + node.left && queue.push(node.left); + } + return true; +}; +``` + ## C 递归法: ```c From f1a3fbc78851c01bb2b97cf004c85b3d15f41970 Mon Sep 17 00:00:00 2001 From: Anmizi <1845513904@qq.com> Date: Sun, 6 Feb 2022 23:33:11 +0800 Subject: [PATCH 115/257] =?UTF-8?q?Update=200110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改原有JS版本代码问题 --- problems/0110.平衡二叉树.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 9d43407a..313aeff2 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -614,8 +614,10 @@ var isBalanced = function(root) { if(node === null) return 0; // 3. 确定单层递归逻辑 let leftDepth = getDepth(node.left); //左子树高度 - let rightDepth = getDepth(node.right); //右子树高度 + // 当判定左子树不为平衡二叉树时,即可直接返回-1 if(leftDepth === -1) return -1; + let rightDepth = getDepth(node.right); //右子树高度 + // 当判定右子树不为平衡二叉树时,即可直接返回-1 if(rightDepth === -1) return -1; if(Math.abs(leftDepth - rightDepth) > 1) { return -1; From 8ce87963e5fe7e74657109d71c80ce3ce3b07da6 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, 7 Feb 2022 13:29:05 +0800 Subject: [PATCH 116/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=EF=BC=9A=E4=BB=A5=E4=B8=BA=E4=BD=BF=E7=94=A8=E4=BA=86?= =?UTF-8?q?=E9=80=92=E5=BD=92=EF=BC=8C=E5=85=B6=E5=AE=9E=E8=BF=98=E9=9A=90?= =?UTF-8?q?=E8=97=8F=E7=9D=80=E5=9B=9E=E6=BA=AF=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树中递归带着回溯.md | 55 ++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 20b87f87..603854dc 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -515,6 +515,61 @@ var binaryTreePaths = function(root) { }; ``` +Swift: +> 100.相同的树 +```swift +// 递归 +func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { + return _isSameTree3(p, q) +} +func _isSameTree3(_ p: TreeNode?, _ q: TreeNode?) -> Bool { + if p == nil && q == nil { + return true + } else if p == nil && q != nil { + return false + } else if p != nil && q == nil { + return false + } else if p!.val != q!.val { + return false + } + let leftSide = _isSameTree3(p!.left, q!.left) + let rightSide = _isSameTree3(p!.right, q!.right) + return leftSide && rightSide +} +``` + +> 257.二叉树的不同路径 +```swift +// 递归/回溯 +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var paths = [Int]() + _binaryTreePaths3(root, res: &res, paths: &paths) + return res +} +func _binaryTreePaths3(_ root: TreeNode, res: inout [String], paths: inout [Int]) { + paths.append(root.val) + if root.left == nil && root.right == nil { + var str = "" + for i in 0 ..< (paths.count - 1) { + str.append("\(paths[i])->") + } + str.append("\(paths.last!)") + res.append(str) + } + if let left = root.left { + _binaryTreePaths3(left, res: &res, paths: &paths) + paths.removeLast() + } + if let right = root.right { + _binaryTreePaths3(right, res: &res, paths: &paths) + paths.removeLast() + } +} +``` -----------------------
From 3aa54bfb8a8604a8cfb05a4fa8c606ebe6b09db3 Mon Sep 17 00:00:00 2001 From: Wayne <3522373084@qq.com> Date: Mon, 7 Feb 2022 21:39:51 +0800 Subject: [PATCH 117/257] =?UTF-8?q?343=E6=95=B4=E6=95=B0=E6=8B=86=E5=88=86?= =?UTF-8?q?,=E6=9B=B4=E6=96=B0=E7=AC=AC=E4=BA=8C=E5=B1=82=E5=BE=AA?= =?UTF-8?q?=E7=8E=AF=20j=20=E7=9A=84=E8=8C=83=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0343.整数拆分.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 5d11f670..f616a606 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -197,14 +197,17 @@ Java: ```Java class Solution { public int integerBreak(int n) { - //dp[i]为正整数i拆分结果的最大乘积 - int[] dp = new int[n+1]; - dp[2] = 1; - for (int i = 3; i <= n; ++i) { - for (int j = 1; j < i - 1; ++j) { - //j*(i-j)代表把i拆分为j和i-j两个数相乘 - //j*dp[i-j]代表把i拆分成j和继续把(i-j)这个数拆分,取(i-j)拆分结果中的最大乘积与j相乘 - dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j])); + //dp[i] 为正整数 i 拆分后的结果的最大乘积 + int[]dp=new int[n+1]; + dp[2]=1; + for(int i=3;i<=n;i++){ + for(int j=1;j<=i-j;j++){ + // 这里的 j 其实最大值为 i-j,再大只不过是重复而已, + //并且,在本题中,我们分析 dp[0], dp[1]都是无意义的, + //j 最大到 i-j,就不会用到 dp[0]与dp[1] + dp[i]=Math.max(dp[i],Math.max(j*(i-j),j*dp[i-j])); + // j * (i - j) 是单纯的把整数 i 拆分为两个数 也就是 i,i-j ,再相乘 + //而j * dp[i - j]是将 i 拆分成两个以及两个以上的个数,再相乘。 } } return dp[n]; From 1b7c86e20c2b36ed0732deb66a0c124a8e8fcdff Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 7 Feb 2022 23:01:47 +0800 Subject: [PATCH 118/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880257.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF?= =?UTF-8?q?=E5=BE=84.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0257.二叉树的所有路径.md | 67 ++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 6 deletions(-) diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 4078320f..1362897c 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -433,9 +433,9 @@ class Solution: if cur.right: self.traversal(cur.right, path + '->', result) ``` - + 迭代法: - + ```python3 from collections import deque @@ -463,13 +463,13 @@ class Solution: return result ``` - + --- Go: - + 递归法: - + ```go func binaryTreePaths(root *TreeNode) []string { res := make([]string, 0) @@ -492,7 +492,7 @@ func binaryTreePaths(root *TreeNode) []string { return res } ``` - + 迭代法: ```go @@ -581,7 +581,62 @@ var binaryTreePaths = function(root) { }; ``` +TypeScript: + +> 递归法 + +```typescript +function binaryTreePaths(root: TreeNode | null): string[] { + function recur(node: TreeNode, route: string, resArr: string[]): void { + route += String(node.val); + if (node.left === null && node.right === null) { + resArr.push(route); + return; + } + if (node.left !== null) recur(node.left, route + '->', resArr); + if (node.right !== null) recur(node.right, route + '->', resArr); + } + const resArr: string[] = []; + if (root === null) return resArr; + recur(root, '', resArr); + return resArr; +}; +``` + +> 迭代法 + +```typescript +// 迭代法2 +function binaryTreePaths(root: TreeNode | null): string[] { + let helperStack: TreeNode[] = []; + let tempNode: TreeNode; + let routeArr: string[] = []; + let resArr: string[] = []; + if (root !== null) { + helperStack.push(root); + routeArr.push(String(root.val)); + }; + while (helperStack.length > 0) { + tempNode = helperStack.pop()!; + let route: string = routeArr.pop()!; // tempNode 对应的路径 + if (tempNode.left === null && tempNode.right === null) { + resArr.push(route); + } + if (tempNode.right !== null) { + helperStack.push(tempNode.right); + routeArr.push(route + '->' + tempNode.right.val); // tempNode.right 对应的路径 + } + if (tempNode.left !== null) { + helperStack.push(tempNode.left); + routeArr.push(route + '->' + tempNode.left.val); // tempNode.left 对应的路径 + } + } + return resArr; +}; +``` + Swift: + > 递归/回溯 ```swift func binaryTreePaths(_ root: TreeNode?) -> [String] { From 47818c947888ecff3dae6f36daded1cfaf92db3b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 8 Feb 2022 10:23:59 +0800 Subject: [PATCH 119/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E4=B8=AD=E9=80=92=E5=BD=92=E5=B8=A6=E7=9D=80?= =?UTF-8?q?=E5=9B=9E=E6=BA=AF.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=9B=B8=E5=90=8C=E7=9A=84=E6=A0=91typescript=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/二叉树中递归带着回溯.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 20b87f87..03815ed3 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -515,6 +515,29 @@ var binaryTreePaths = function(root) { }; ``` +TypeScript: + +> 相同的树 + +```typescript +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p === null && q === null) return true; + if (p === null || q === null) return false; + if (p.val !== q.val) return false; + let bool1: boolean, bool2: boolean; + bool1 = isSameTree(p.left, q.left); + bool2 = isSameTree(p.right, q.right); + return bool1 && bool2; +}; +``` + +> 二叉树的不同路径 + +```typescript +``` + + + -----------------------
From 49a1a42bbed494b10b4d6659ba787830f62bd842 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 8 Feb 2022 10:45:15 +0800 Subject: [PATCH 120/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E4=B8=AD=E9=80=92=E5=BD=92=E5=B8=A6=E7=9D=80?= =?UTF-8?q?=E5=9B=9E=E6=BA=AF.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E4=B8=8D=E5=90=8C=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E7=9A=84typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树中递归带着回溯.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 03815ed3..41d5663e 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.md @@ -534,6 +534,27 @@ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { > 二叉树的不同路径 ```typescript +function binaryTreePaths(root: TreeNode | null): string[] { + function recur(node: TreeNode, nodeSeqArr: number[], resArr: string[]): void { + nodeSeqArr.push(node.val); + if (node.left === null && node.right === null) { + resArr.push(nodeSeqArr.join('->')); + } + if (node.left !== null) { + recur(node.left, nodeSeqArr, resArr); + nodeSeqArr.pop(); + } + if (node.right !== null) { + recur(node.right, nodeSeqArr, resArr); + nodeSeqArr.pop(); + } + } + let nodeSeqArr: number[] = []; + let resArr: string[] = []; + if (root === null) return resArr; + recur(root, nodeSeqArr, resArr); + return resArr; +}; ``` From f604aea34c6632e20ad4ced37cb24c005420e574 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 8 Feb 2022 23:00:31 +0800 Subject: [PATCH 121/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880404.?= =?UTF-8?q?=E5=B7=A6=E5=8F=B6=E5=AD=90=E4=B9=8B=E5=92=8C.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/0404.左叶子之和.md | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 09272052..2b4df151 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -372,6 +372,50 @@ var sumOfLeftLeaves = function(root) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function sumOfLeftLeaves(root: TreeNode | null): number { + if (root === null) return 0; + let midVal: number = 0; + if ( + root.left !== null && + root.left.left === null && + root.left.right === null + ) { + midVal = root.left.val; + } + let leftVal: number = sumOfLeftLeaves(root.left); + let rightVal: number = sumOfLeftLeaves(root.right); + return midVal + leftVal + rightVal; +}; +``` + +> 迭代法 + +```typescript +function sumOfLeftLeaves(root: TreeNode | null): number { + let helperStack: TreeNode[] = []; + let tempNode: TreeNode; + let sum: number = 0; + if (root !== null) helperStack.push(root); + while (helperStack.length > 0) { + tempNode = helperStack.pop()!; + if ( + tempNode.left !== null && + tempNode.left.left === null && + tempNode.left.right === null + ) { + sum += tempNode.left.val; + } + if (tempNode.right !== null) helperStack.push(tempNode.right); + if (tempNode.left !== null) helperStack.push(tempNode.left); + } + return sum; +}; +``` ## Swift From 81c1060ad7b21cab48d3f27aea802135544a73ff Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Wed, 9 Feb 2022 14:57:04 +0800 Subject: [PATCH 122/257] Update --- README.md | 9 +++++---- problems/前序/程序员写文档工具.md | 1 - problems/背包理论基础01背包-2.md | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index c5149776..c1761f7b 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,11 @@ > 1. **介绍**:本项目是一套完整的刷题计划,旨在帮助大家少走弯路,循序渐进学算法,[关注作者](#关于作者) > 2. **PDF版本** : [「代码随想录」算法精讲 PDF 版本](https://programmercarl.com/other/algo_pdf.html) 。 -> 3. **刷题顺序** : README已经将刷题顺序排好了,按照顺序一道一道刷就可以。 -> 4. **学习社区** : 一起学习打卡/面试技巧/如何选择offer/大厂内推/职场规则/简历修改/技术分享/程序人生。欢迎加入[「代码随想录」知识星球](https://programmercarl.com/other/kstar.html) 。 -> 5. **提交代码**:本项目统一使用C++语言进行讲解,但已经有Java、Python、Go、JavaScript等等多语言版本,感谢[这里的每一位贡献者](https://github.com/youngyangyang04/leetcode-master/graphs/contributors),如果你也想贡献代码点亮你的头像,[点击这里](https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A)了解提交代码的方式。 -> 6. **转载须知** :以下所有文章皆为我([程序员Carl](https://github.com/youngyangyang04))的原创。引用本项目文章请注明出处,发现恶意抄袭或搬运,会动用法律武器维护自己的权益。让我们一起维护一个良好的技术创作环境! +> 3. **最强八股文:**:[代码随想录知识星球精华PDF](https://www.programmercarl.com/other/kstar_baguwen.html) +> 4. **刷题顺序** : README已经将刷题顺序排好了,按照顺序一道一道刷就可以。 +> 5. **学习社区** : 一起学习打卡/面试技巧/如何选择offer/大厂内推/职场规则/简历修改/技术分享/程序人生。欢迎加入[「代码随想录」知识星球](https://programmercarl.com/other/kstar.html) 。 +> 6. **提交代码**:本项目统一使用C++语言进行讲解,但已经有Java、Python、Go、JavaScript等等多语言版本,感谢[这里的每一位贡献者](https://github.com/youngyangyang04/leetcode-master/graphs/contributors),如果你也想贡献代码点亮你的头像,[点击这里](https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A)了解提交代码的方式。 +> 7. **转载须知** :以下所有文章皆为我([程序员Carl](https://github.com/youngyangyang04))的原创。引用本项目文章请注明出处,发现恶意抄袭或搬运,会动用法律武器维护自己的权益。让我们一起维护一个良好的技术创作环境!

diff --git a/problems/前序/程序员写文档工具.md b/problems/前序/程序员写文档工具.md index b76fb036..e4193c42 100644 --- a/problems/前序/程序员写文档工具.md +++ b/problems/前序/程序员写文档工具.md @@ -135,7 +135,6 @@ Markdown支持部分html,例如这样 - ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index a57bae10..dabdfb2d 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -210,7 +210,7 @@ int main() { ## 其他语言版本 -Java: +### Java ```java public static void main(String[] args) { @@ -240,7 +240,7 @@ Java: -Python: +### Python ```python def test_1_wei_bag_problem(): weight = [1, 3, 4] @@ -260,7 +260,7 @@ def test_1_wei_bag_problem(): test_1_wei_bag_problem() ``` -Go: +### Go ```go func test_1_wei_bag_problem(weight, value []int, bagWeight int) int { // 定义 and 初始化 @@ -292,7 +292,7 @@ func main() { } ``` -javaScript: +### javaScript ```js From 4ed65b50d174a3d9f89d0352ee30da95fcecece9 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 9 Feb 2022 22:45:31 +0800 Subject: [PATCH 123/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880513.?= =?UTF-8?q?=E6=89=BE=E6=A0=91=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC?= =?UTF-8?q?.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/0513.找树左下角的值.md | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 84ed3932..12c62c70 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -433,6 +433,51 @@ var findBottomLeftValue = function(root) { }; ``` +## TypeScript + +> 递归法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + function recur(root: TreeNode, depth: number): void { + if (root.left === null && root.right === null) { + if (depth > maxDepth) { + maxDepth = depth; + resVal = root.val; + } + return; + } + if (root.left !== null) recur(root.left, depth + 1); + if (root.right !== null) recur(root.right, depth + 1); + } + let maxDepth: number = 0; + let resVal: number = 0; + if (root === null) return resVal; + recur(root, 1); + return resVal; +}; +``` + +> 迭代法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + if (root !== null) helperQueue.push(root); + let resVal: number = 0; + let tempNode: TreeNode; + while (helperQueue.length > 0) { + resVal = helperQueue[0].val; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resVal; +}; +``` + ## Swift 递归版本: From 7d8e9e8fae9d580013b717ff882bd9a942fe0e4f Mon Sep 17 00:00:00 2001 From: Guang-Hou <87743934+Guang-Hou@users.noreply.github.com> Date: Wed, 9 Feb 2022 16:37:44 -0500 Subject: [PATCH 124/257] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E6=93=8D=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Python 递归法- 无返回值的一种更简单的实现。 --- problems/0701.二叉搜索树中的插入操作.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 468f2675..5e9fbdfe 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -310,6 +310,26 @@ class Solution: return root ``` +**递归法** - 无返回值 - another easier way +```python +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + newNode = TreeNode(val) + if not root: return newNode + + if not root.left and val < root.val: + root.left = newNode + if not root.right and val > root.val: + root.right = newNode + + if val < root.val: + self.insertIntoBST(root.left, val) + if val > root.val: + self.insertIntoBST(root.right, val) + + return root +``` + **迭代法** 与无返回值的递归函数的思路大体一致 ```python From fc1a7e3e079958e6919bbc4fbe069a8d92e66322 Mon Sep 17 00:00:00 2001 From: zhaoninge Date: Thu, 10 Feb 2022 17:01:31 +0800 Subject: [PATCH 125/257] =?UTF-8?q?Update=200027.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加27. 移除元素 C++版相向双指针方法,该方法基于元素顺序可以改变的题目描述,使用双指针法改变了元素相对位置,确保了移动最少元素 --- problems/0027.移除元素.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index d69f2bcf..0c6f5129 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -106,6 +106,37 @@ public: 旧文链接:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html) +```CPP +/** +* 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素 +* 时间复杂度:$O(n)$ +* 空间复杂度:$O(1)$ +*/ +class Solution { +public: + int removeElement(vector& nums, int val) { + int leftIndex = 0; + int rightIndex = nums.size() - 1; + while (leftIndex <= rightIndex) { + // 找左边等于val的元素 + while (leftIndex <= rightIndex && nums[leftIndex] != val){ + ++leftIndex; + } + // 找右边不等于val的元素 + while (leftIndex <= rightIndex && nums[rightIndex] == val) { + -- rightIndex; + } + // 将右边不等于val的元素覆盖左边等于val的元素 + if (leftIndex < rightIndex) { + nums[leftIndex++] = nums[rightIndex--]; + } + } + return leftIndex; // leftIndex一定指向了最终数组末尾的下一个元素 + } +}; +``` + + ## 相关题目推荐 * 26.删除排序数组中的重复项 From 71dd3eab9e9a005eec5669bfc25ba3cd4d27fb2f Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Fri, 11 Feb 2022 11:26:14 +0800 Subject: [PATCH 126/257] =?UTF-8?q?0059=20=20=E8=9E=BA=E6=97=8B=E7=9F=A9?= =?UTF-8?q?=E9=98=B5II=20=20=E9=A2=98=E7=9B=AE=E9=94=99=E8=AF=AF=E7=BA=A0?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 3f7a59ca..ff654358 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -10,7 +10,7 @@ [力扣题目链接](https://leetcode-cn.com/problems/spiral-matrix-ii/) -给定一个正整数 n,生成一个包含 1 到 $n^2$ 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 +给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例: From 305ef69d5878ecaf1b9655e7899d663290f53af5 Mon Sep 17 00:00:00 2001 From: weiting-cn <2254912@qq.com> Date: Fri, 11 Feb 2022 16:09:17 +0800 Subject: [PATCH 127/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=EF=BC=9A0015.?= =?UTF-8?q?=E4=B8=89=E6=95=B0=E4=B9=8B=E5=92=8C=EF=BC=8C0018.=E5=9B=9B?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=EF=BC=88=E5=8E=BB=E9=87=8D=E4=BC=98?= =?UTF-8?q?=E5=8C=96=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0015.三数之和.md | 4 ++++ problems/0018.四数之和.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index e191eabc..9b59e66d 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -138,8 +138,12 @@ public: */ if (nums[i] + nums[left] + nums[right] > 0) { right--; + // 当前元素不合适了,可以去重 + while (left < right && nums[right] == nums[right + 1]) right--; } else if (nums[i] + nums[left] + nums[right] < 0) { left++; + // 不合适,去重 + while (left < right && nums[left] == nums[left - 1]) left++; } else { result.push_back(vector{nums[i], nums[left], nums[right]}); // 去重逻辑应该放在找到一个三元组之后 diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index bad258c1..c6c55d50 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -91,9 +91,13 @@ public: // nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出 if (nums[k] + nums[i] > target - (nums[left] + nums[right])) { right--; + // 当前元素不合适了,可以去重 + while (left < right && nums[right] == nums[right + 1]) right--; // nums[k] + nums[i] + nums[left] + nums[right] < target 会溢出 } else if (nums[k] + nums[i] < target - (nums[left] + nums[right])) { left++; + // 不合适,去重 + while (left < right && nums[left] == nums[left - 1]) left++; } else { result.push_back(vector{nums[k], nums[i], nums[left], nums[right]}); // 去重逻辑应该放在找到一个四元组之后 From fbf52ee2bf0cad8c4231311ef2d87fc383a49a3c Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Fri, 11 Feb 2022 16:57:22 +0800 Subject: [PATCH 128/257] =?UTF-8?q?=E7=AE=97=E6=B3=95=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=20typescript=20=E7=89=88=E6=9C=AC=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/算法模板.md | 265 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 264 insertions(+), 1 deletion(-) diff --git a/problems/算法模板.md b/problems/算法模板.md index a4136511..789d8f80 100644 --- a/problems/算法模板.md +++ b/problems/算法模板.md @@ -394,7 +394,7 @@ var postorder = function (root, list) { ```javascript var preorderTraversal = function (root) { let res = []; - if (root === null) return rs; + if (root === null) return res; let stack = [root], cur = null; while (stack.length) { @@ -536,6 +536,269 @@ function backtracking(参数) { } ``` +TypeScript: + +## 二分查找法 + +使用左闭右闭区间 + +```typescript +var search = function (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 +var search = function (nums: number[], target: number): number { + let left: number = 0, right: number = nums.length; + // 使用左闭右开区间 [left, right) + 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; +}; +``` + +## KMP + +```typescript +var kmp = function (next: number[], s: number): void { + next[0] = -1; + let j: number = -1; + for(let i: number = 1; i < s.length; i++){ + while (j >= 0 && s[i] !== s[j + 1]) { + j = next[j]; + } + if (s[i] === s[j + 1]) { + j++; + } + next[i] = j; + } +} +``` + +## 二叉树 + +### 深度优先遍历(递归) + +二叉树节点定义: + +```typescript +class TreeNode { + val: number + left: TreeNode | null + right: TreeNode | null + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + this.val = (val===undefined ? 0 : val) + this.left = (left===undefined ? null : left) + this.right = (right===undefined ? null : right) + } +} +``` + +前序遍历(中左右): + +```typescript +var preorder = function (root: TreeNode | null, list: number[]): void { + if (root === null) return; + list.push(root.val); // 中 + preorder(root.left, list); // 左 + preorder(root.right, list); // 右 +} +``` + +中序遍历(左中右): + +```typescript +var inorder = function (root: TreeNode | null, list: number[]): void { + if (root === null) return; + inorder(root.left, list); // 左 + list.push(root.val); // 中 + inorder(root.right, list); // 右 +} +``` + +后序遍历(左右中): + +```typescript +var postorder = function (root: TreeNode | null, list: number[]): void { + if (root === null) return; + postorder(root.left, list); // 左 + postorder(root.right, list); // 右 + list.push(root.val); // 中 +} +``` + +### 深度优先遍历(迭代) + +前序遍历(中左右): + +```typescript +var preorderTraversal = function (root: TreeNode | null): number[] { + let res: number[] = []; + if (root === null) return res; + let stack: TreeNode[] = [root], + cur: TreeNode | null = null; + while (stack.length) { + cur = stack.pop(); + res.push(cur.val); + cur.right && stack.push(cur.right); + cur.left && stack.push(cur.left); + } + return res; +}; +``` + +中序遍历(左中右): + +```typescript +var inorderTraversal = function (root: TreeNode | null): number[] { + let res: number[] = []; + if (root === null) return res; + let stack: TreeNode[] = []; + let cur: TreeNode | null = root; + while (stack.length !== 0 || cur !== null) { + if (cur !== null) { + stack.push(cur); + cur = cur.left; + } else { + cur = stack.pop(); + res.push(cur.val); + cur = cur.right; + } + } + return res; +}; +``` + +后序遍历(左右中): + +```typescript +var postorderTraversal = function (root: TreeNode | null): number[] { + let res: number[] = []; + if (root === null) return res; + let stack: TreeNode[] = [root]; + let cur: TreeNode | null = null; + while (stack.length) { + cur = stack.pop(); + res.push(cur.val); + cur.left && stack.push(cur.left); + cur.right && stack.push(cur.right); + } + return res.reverse() +}; +``` + +### 广度优先遍历(队列) + +```typescript +var levelOrder = function (root: TreeNode | null): number[] { + let res: number[] = []; + if (root === null) return res; + let queue: TreeNode[] = [root]; + while (queue.length) { + let n: number = queue.length; + let temp: number[] = []; + for (let i: number = 0; i < n; i++) { + let node: TreeNode = queue.shift(); + temp.push(node.val); + node.left && queue.push(node.left); + node.right && queue.push(node.right); + } + res.push(temp); + } + return res; +}; +``` + +### 二叉树深度 + +```typescript +var getDepth = function (node: TreNode | null): number { + if (node === null) return 0; + return 1 + Math.max(getDepth(node.left), getDepth(node.right)); +} +``` + +### 二叉树节点数量 + +```typescript +var countNodes = function (root: TreeNode | null): number { + if (root === null) return 0; + return 1 + countNodes(root.left) + countNodes(root.right); +} +``` + +## 回溯算法 + +```typescript +function backtracking(参数) { + if (终止条件) { + 存放结果; + return; + } + + for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) { + 处理节点; + backtracking(路径,选择列表); // 递归 + 回溯,撤销处理结果 + } +} + +``` + +## 并查集 + +```typescript + let n: number = 1005; // 根据题意而定 + let father: number[] = new Array(n).fill(0); + + // 并查集初始化 + function init () { + for (int i: number = 0; i < n; ++i) { + father[i] = i; + } + } + // 并查集里寻根的过程 + function find (u: number): number { + return u === father[u] ? u : father[u] = find(father[u]); + } + // 将v->u 这条边加入并查集 + function join(u: number, v: number) { + u = find(u); + v = find(v); + if (u === v) return ; + father[v] = u; + } + // 判断 u 和 v是否找到同一个根 + function same(u: number, v: number): boolean { + u = find(u); + v = find(v); + return u === v; + } +``` + Java: From 65a341bf365eb3b2648c357a7a311a59ec6e9e18 Mon Sep 17 00:00:00 2001 From: Larry Liu Date: Fri, 11 Feb 2022 20:24:45 +0800 Subject: [PATCH 129/257] =?UTF-8?q?Update=20=E5=B9=BF=E5=B7=9E=E4=BA=92?= =?UTF-8?q?=E8=81=94=E7=BD=91=E5=85=AC=E5=8F=B8=E6=80=BB=E7=BB=93.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 字节跳动有广州研发岗位 --- problems/前序/广州互联网公司总结.md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/前序/广州互联网公司总结.md b/problems/前序/广州互联网公司总结.md index ae41c899..ac70f40c 100644 --- a/problems/前序/广州互联网公司总结.md +++ b/problems/前序/广州互联网公司总结.md @@ -14,6 +14,7 @@ ## 一线互联网 * 微信(总部) 有点难进! +* 字节跳动(广州) ## 二线 * 网易(总部)主要是游戏 From 961ae6eadf6359f2ef6b787ad612475e02e6842e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 11 Feb 2022 21:52:36 +0800 Subject: [PATCH 130/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880112.?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E6=80=BB=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 89 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5ec8ffd0..de6caef0 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -766,11 +766,100 @@ let pathSum = function(root, targetSum) { }; ``` +## TypeScript + +> 0112.路径总和 + +**递归法:** + +```typescript +function hasPathSum(root: TreeNode | null, targetSum: number): boolean { + function recur(node: TreeNode, sum: number): boolean { + console.log(sum); + if ( + node.left === null && + node.right === null && + sum === 0 + ) return true; + if (node.left !== null) { + sum -= node.left.val; + if (recur(node.left, sum) === true) return true; + sum += node.left.val; + } + if (node.right !== null) { + sum -= node.right.val; + if (recur(node.right, sum) === true) return true; + sum += node.right.val; + } + return false; + } + if (root === null) return false; + return recur(root, targetSum - root.val); +}; +``` + +**递归法(精简版):** + +```typescript +function hasPathSum(root: TreeNode | null, targetSum: number): boolean { + if (root === null) return false; + targetSum -= root.val; + if ( + root.left === null && + root.right === null && + targetSum === 0 + ) return true; + return hasPathSum(root.left, targetSum) || + hasPathSum(root.right, targetSum); +}; +``` + +**迭代法:** + +```typescript +function hasPathSum(root: TreeNode | null, targetSum: number): boolean { + type Pair = { + node: TreeNode, // 当前节点 + sum: number // 根节点到当前节点的路径数值总和 + } + + const helperStack: Pair[] = []; + if (root !== null) helperStack.push({ node: root, sum: root.val }); + let tempPair: Pair; + while (helperStack.length > 0) { + tempPair = helperStack.pop()!; + if ( + tempPair.node.left === null && + tempPair.node.right === null && + tempPair.sum === targetSum + ) return true; + if (tempPair.node.right !== null) { + helperStack.push({ + node: tempPair.node.right, + sum: tempPair.sum + tempPair.node.right.val + }); + } + if (tempPair.node.left !== null) { + helperStack.push({ + node: tempPair.node.left, + sum: tempPair.sum + tempPair.node.left.val + }); + } + } + return false; +}; +``` + +> 0112.路径总和 ii + + + ## Swift 0112.路径总和 **递归** + ```swift func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { guard let root = root else { From fde074cb2ab400b44707c178139d7757541bbf39 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 11 Feb 2022 23:28:30 +0800 Subject: [PATCH 131/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880112.?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E6=80=BB=E5=92=8C=20ii=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0112.路径总和.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index de6caef0..2e10d98d 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -852,7 +852,39 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean { > 0112.路径总和 ii +**递归法:** +```typescript +function pathSum(root: TreeNode | null, targetSum: number): number[][] { + function recur(node: TreeNode, sumGap: number, routeArr: number[]): void { + if ( + node.left === null && + node.right === null && + sumGap === 0 + ) resArr.push([...routeArr]); + if (node.left !== null) { + sumGap -= node.left.val; + routeArr.push(node.left.val); + recur(node.left, sumGap, routeArr); + sumGap += node.left.val; + routeArr.pop(); + } + if (node.right !== null) { + sumGap -= node.right.val; + routeArr.push(node.right.val); + recur(node.right, sumGap, routeArr); + sumGap += node.right.val; + routeArr.pop(); + } + } + const resArr: number[][] = []; + if (root === null) return resArr; + const routeArr: number[] = []; + routeArr.push(root.val); + recur(root, targetSum - root.val, routeArr); + return resArr; +}; +``` ## Swift From fb67fb4320c3ee7c0ee17dd695a5b7a7ea2a4d34 Mon Sep 17 00:00:00 2001 From: "darion.yaphet" Date: Sat, 12 Feb 2022 17:25:57 +0800 Subject: [PATCH 132/257] fix java code --- problems/背包理论基础01背包-1.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 6ff32017..fe940b4c 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -271,7 +271,7 @@ int main() { ### java ```java - public static void main(string[] args) { + public static void main(String[] args) { int[] weight = {1, 3, 4}; int[] value = {15, 20, 30}; int bagsize = 4; @@ -292,16 +292,16 @@ int main() { if (j < weight[i - 1]){ dp[i][j] = dp[i - 1][j]; }else{ - dp[i][j] = math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]); + dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]); } } } //打印dp数组 for (int i = 0; i <= wlen; i++){ for (int j = 0; j <= bagsize; j++){ - system.out.print(dp[i][j] + " "); + System.out.print(dp[i][j] + " "); } - system.out.print("\n"); + System.out.print("\n"); } } ``` From bac5f8d70cef72f5457ac80fd487d86618d27831 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 13 Feb 2022 16:37:32 +0800 Subject: [PATCH 133/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880106.?= =?UTF-8?q?=E4=BB=8E=E4=B8=AD=E5=BA=8F=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0106.从中序与后序遍历序列构造二叉树.md | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 40d75983..9b18e729 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -814,7 +814,70 @@ var buildTree = function(preorder, inorder) { }; ``` +## TypeScript + +> 106.从中序与后序遍历序列构造二叉树 + +**创建新数组:** + +```typescript +function buildTree(inorder: number[], postorder: number[]): TreeNode | null { + if (postorder.length === 0) return null; + const rootVal: number = postorder.pop()!; + const rootValIndex: number = inorder.indexOf(rootVal); + const rootNode: TreeNode = new TreeNode(rootVal); + rootNode.left = buildTree(inorder.slice(0, rootValIndex), postorder.slice(0, rootValIndex)); + rootNode.right = buildTree(inorder.slice(rootValIndex + 1), postorder.slice(rootValIndex)); + return rootNode; +}; +``` + +**使用数组索引:** + +```typescript +function buildTree(inorder: number[], postorder: number[]): TreeNode | null { + function recur( + inorder: number[], postorder: number[], + inBegin: number, inEnd: number, + postBegin: number, postEnd: number + ): TreeNode | null { + if (postBegin === postEnd) return null; + const rootVal: number = postorder[postEnd - 1]!; + const rootValIndex: number = inorder.indexOf(rootVal, inBegin); + const rootNode: TreeNode = new TreeNode(rootVal); + + const leftInorderBegin: number = inBegin; + const leftInorderEnd: number = rootValIndex; + const rightInorderBegin: number = rootValIndex + 1; + const rightInorderEnd: number = inEnd; + + const leftPostorderBegin: number = postBegin; + const leftPostorderEnd: number = postBegin + rootValIndex - inBegin; + const rightPostorderBegin: number = leftPostorderEnd; + const rightPostorderEnd: number = postEnd - 1; + + rootNode.left = recur( + inorder, postorder, + leftInorderBegin, leftInorderEnd, + leftPostorderBegin, leftPostorderEnd + ); + rootNode.right = recur( + inorder, postorder, + rightInorderBegin, rightInorderEnd, + rightPostorderBegin, rightPostorderEnd + ); + return rootNode; + } + return recur(inorder, postorder, 0, inorder.length, 0, inorder.length); +}; +``` + +> 105.从前序与中序遍历序列构造二叉树 + + + ## C + 106 从中序与后序遍历序列构造二叉树 ```c From ddf79ac04322e27c50f50be81a46407d7b054950 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 13 Feb 2022 17:09:38 +0800 Subject: [PATCH 134/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88105.?= =?UTF-8?q?=E4=BB=8E=E5=89=8D=E5=BA=8F=E4=B8=8E=E4=B8=AD=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86=E5=BA=8F=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0106.从中序与后序遍历序列构造二叉树.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 9b18e729..3e4211fb 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -874,7 +874,51 @@ function buildTree(inorder: number[], postorder: number[]): TreeNode | null { > 105.从前序与中序遍历序列构造二叉树 +**新建数组:** +```typescript +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { + if (preorder.length === 0) return null; + const rootVal: number = preorder[0]; + const rootNode: TreeNode = new TreeNode(rootVal); + const rootValIndex: number = inorder.indexOf(rootVal); + rootNode.left = buildTree(preorder.slice(1, rootValIndex + 1), inorder.slice(0, rootValIndex)); + rootNode.right = buildTree(preorder.slice(rootValIndex + 1), inorder.slice(rootValIndex + 1)); + return rootNode; +}; +``` + +**使用数组索引:** + +```typescript +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { + function recur( + preorder: number[], inorder: number[], + preBegin: number, preEnd: number, + inBegin: number, inEnd: number + ): TreeNode | null { + if (preBegin === preEnd) return null; + const rootVal: number = preorder[preBegin]; + const rootNode: TreeNode = new TreeNode(rootVal); + const rootValIndex: number = inorder.indexOf(rootVal, inBegin); + + const leftPreBegin: number = preBegin + 1; + const leftPreEnd: number = preBegin + rootValIndex - inBegin + 1; + const leftInBegin: number = inBegin; + const leftInEnd: number = rootValIndex; + + const rightPreBegin: number = leftPreEnd; + const rightPreEnd: number = preEnd; + const rightInBegin: number = rootValIndex + 1; + const rightInEnd: number = inEnd; + + rootNode.left = recur(preorder, inorder, leftPreBegin, leftPreEnd, leftInBegin, leftInEnd); + rootNode.right = recur(preorder, inorder, rightPreBegin, rightPreEnd, rightInBegin, rightInEnd); + return rootNode; + }; + return recur(preorder, inorder, 0, preorder.length, 0, inorder.length); +}; +``` ## C From 92322870fe4664dffa3dcb8e6020626376417bb3 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 13 Feb 2022 21:20:24 +0800 Subject: [PATCH 135/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880654.?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E4=BA=8C=E5=8F=89=E6=A0=91.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/0654.最大二叉树.md | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 44c74f89..1c73354b 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -371,7 +371,56 @@ var constructMaximumBinaryTree = function (nums) { }; ``` +## TypeScript + +> 新建数组法: + +```typescript +function constructMaximumBinaryTree(nums: number[]): TreeNode | null { + if (nums.length === 0) return null; + let maxIndex: number = 0; + let maxVal: number = nums[0]; + for (let i = 1, length = nums.length; i < length; i++) { + if (nums[i] > maxVal) { + maxIndex = i; + maxVal = nums[i]; + } + } + const rootNode: TreeNode = new TreeNode(maxVal); + rootNode.left = constructMaximumBinaryTree(nums.slice(0, maxIndex)); + rootNode.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1)); + return rootNode; +}; +``` + +> 使用数组索引法: + +```typescript +function constructMaximumBinaryTree(nums: number[]): TreeNode | null { + // 左闭右开区间[begin, end) + function recur(nums: number[], begin: number, end: number): TreeNode | null { + if (begin === end) return null; + let maxIndex: number = begin; + let maxVal: number = nums[begin]; + for (let i = begin + 1; i < end; i++) { + if (nums[i] > maxVal) { + maxIndex = i; + maxVal = nums[i]; + } + } + const rootNode: TreeNode = new TreeNode(maxVal); + rootNode.left = recur(nums, begin, maxIndex); + rootNode.right = recur(nums, maxIndex + 1, end); + return rootNode; + } + return recur(nums, 0, nums.length); +}; +``` + + + ## C + ```c struct TreeNode* traversal(int* nums, int left, int right) { //若左边界大于右边界,返回NULL From 2440d6a365def0caf92f041886545117ec0c1e9f Mon Sep 17 00:00:00 2001 From: Dewittt <43514251+Dewittt@users.noreply.github.com> Date: Mon, 14 Feb 2022 14:04:34 +0800 Subject: [PATCH 136/257] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E8=83=8C=E5=8C=85.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除多余字符 --- problems/背包问题理论基础完全背包.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index cea69c72..2cdfeffa 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -94,7 +94,7 @@ dp状态图如下: 看了这两个图,大家就会理解,完全背包中,两个for循环的先后循序,都不影响计算dp[j]所需要的值(这个值就是下标j之前所对应的dp[j])。 -先遍历被背包在遍历物品,代码如下: +先遍历背包在遍历物品,代码如下: ```CPP // 先遍历背包,再遍历物品 From 30f2c6bc1763bb3cfe607707f96b1d9047a3d2b3 Mon Sep 17 00:00:00 2001 From: Verolilo <57696907+Verolilo@users.noreply.github.com> Date: Mon, 14 Feb 2022 14:15:33 +0800 Subject: [PATCH 137/257] =?UTF-8?q?=E6=9B=B4=E6=96=B00070.=E7=88=AC?= =?UTF-8?q?=E6=A5=BC=E6=A2=AF.md=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新0070.爬楼梯.md python版本,添加了O(1)复杂度的python代码 --- problems/0070.爬楼梯.md | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 7f47a991..da19ea0e 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -256,16 +256,28 @@ public int climbStairs(int n) { ### Python ```python +# 空间复杂度为O(n)版本 class Solution: def climbStairs(self, n: int) -> int: - # dp[i]表示爬到第i级楼梯的种数, (1, 2) (2, 1)是两种不同的类型 - dp = [0] * (n + 1) - dp[0] = 1 - for i in range(n+1): - for j in range(1, 3): - if i>=j: - dp[i] += dp[i-j] - return dp[-1] + # dp[i] 为第 i 阶楼梯有多少种方法爬到楼顶 + dp=[0]*(n+1) + dp[0]=1 + dp[1]=1 + for i in range(2,n+1): + dp[i]=dp[i-1]+dp[i-2] + return dp[n] + +# 空间复杂度为O(1)版本 +class Solution: + def climbStairs(self, n: int) -> int: + dp=[0]*(n+1) + dp[0]=1 + dp[1]=1 + for i in range(2,n+1): + tmp=dp[0]+dp[1] + dp[0]=dp[1] + dp[1]=tmp + return dp[1] ``` ### Go From 6d5a0d0340798f773104f418d3db71797c5db717 Mon Sep 17 00:00:00 2001 From: Verolilo <57696907+Verolilo@users.noreply.github.com> Date: Wed, 16 Feb 2022 10:22:19 +0800 Subject: [PATCH 138/257] =?UTF-8?q?=E6=9B=B4=E6=96=B00213.=E6=89=93?= =?UTF-8?q?=E5=AE=B6=E5=8A=AB=E8=88=8DII.md=20=E6=9B=B4=E7=AE=80=E6=B4=81?= =?UTF-8?q?=E7=9A=84python=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0213.打家劫舍II.md | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index b6c2d080..8e569e46 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -123,22 +123,24 @@ Python: ```Python class Solution: def rob(self, nums: List[int]) -> int: - if (n := len(nums)) == 0: - return 0 - if n == 1: - return nums[0] - result1 = self.robRange(nums, 0, n - 2) - result2 = self.robRange(nums, 1, n - 1) - return max(result1 , result2) + #在198入门级的打家劫舍问题上分两种情况考虑 + #一是不偷第一间房,二是不偷最后一间房 + if len(nums)==1:#题目中提示nums.length>=1,所以不需要考虑len(nums)==0的情况 + return nums[0] + val1=self.roblist(nums[1:])#不偷第一间房 + val2=self.roblist(nums[:-1])#不偷最后一间房 + return max(val1,val2) - def robRange(self, nums: List[int], start: int, end: int) -> int: - if end == start: return nums[start] - dp = [0] * len(nums) - dp[start] = nums[start] - dp[start + 1] = max(nums[start], nums[start + 1]) - for i in range(start + 2, end + 1): - dp[i] = max(dp[i -2] + nums[i], dp[i - 1]) - return dp[end] + def robRange(self,nums): + l=len(nums) + dp=[0]*l + dp[0]=nums[0] + for i in range(1,l): + if i==1: + dp[i]=max(dp[i-1],nums[i]) + else: + dp[i]=max(dp[i-1],dp[i-2]+nums[i]) + return dp[-1] ``` javascipt: From f39d5a110c19963037374a3f1ea253b30f08becb Mon Sep 17 00:00:00 2001 From: erdengk <15596570256@163.com> Date: Wed, 16 Feb 2022 16:23:39 +0800 Subject: [PATCH 139/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E9=94=99=E5=AD=97=20&=20=E4=BC=98=E5=8C=96=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=90=8D=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0106.从中序与后序遍历序列构造二叉树.md | 4 ++-- problems/0860.柠檬水找零.md | 20 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 30ec684d..cb1d75d9 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -89,9 +89,9 @@ TreeNode* traversal (vector& inorder, vector& postorder) { **难点大家应该发现了,就是如何切割,以及边界值找不好很容易乱套。** -此时应该注意确定切割的标准,是左闭右开,还有左开又闭,还是左闭又闭,这个就是不变量,要在递归中保持这个不变量。 +此时应该注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量。 -**在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭又闭,必然乱套!** +**在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭右闭,必然乱套!** 我在[数组:每次遇到二分法,都是一看就会,一写就废](https://programmercarl.com/0035.搜索插入位置.html)和[数组:这个循环可以转懵很多人!](https://programmercarl.com/0059.螺旋矩阵II.html)中都强调过循环不变量的重要性,在二分查找以及螺旋矩阵的求解中,坚持循环不变量非常重要,本题也是。 diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index 01bd1a3b..f48ecf4d 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -128,24 +128,24 @@ public: ```java class Solution { public boolean lemonadeChange(int[] bills) { - int cash_5 = 0; - int cash_10 = 0; + int five = 0; + int ten = 0; for (int i = 0; i < bills.length; i++) { if (bills[i] == 5) { - cash_5++; + five++; } else if (bills[i] == 10) { - cash_5--; - cash_10++; + five--; + ten++; } else if (bills[i] == 20) { - if (cash_10 > 0) { - cash_10--; - cash_5--; + if (ten > 0) { + ten--; + five--; } else { - cash_5 -= 3; + five -= 3; } } - if (cash_5 < 0 || cash_10 < 0) return false; + if (five < 0 || ten < 0) return false; } return true; From 1a553b01d691478c049fd39e59548f3a71c9f456 Mon Sep 17 00:00:00 2001 From: erdengk <15596570256@163.com> Date: Wed, 16 Feb 2022 17:43:36 +0800 Subject: [PATCH 140/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200491.=E9=80=92?= =?UTF-8?q?=E5=A2=9E=E5=AD=90=E5=BA=8F=E5=88=97.md=20Java=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 6d88119e..298586c7 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -227,7 +227,39 @@ class Solution { } } ``` - +```java +//法二:使用map +class Solution { + //结果集合 + List> res = new ArrayList<>(); + //路径集合 + LinkedList path = new LinkedList<>(); + public List> findSubsequences(int[] nums) { + getSubsequences(nums,0); + return res; + } + private void getSubsequences( int[] nums, int start ) { + if(path.size()>1 ){ + res.add( new ArrayList<>(path) ); + // 注意这里不要加return,要取树上的节点 + } + HashMap map = new HashMap<>(); + for(int i=start ;i < nums.length ;i++){ + if(!path.isEmpty() && nums[i]< path.getLast()){ + continue; + } + // 使用过了当前数字 + if ( map.getOrDefault( nums[i],0 ) >=1 ){ + continue; + } + map.put(nums[i],map.getOrDefault( nums[i],0 )+1); + path.add( nums[i] ); + getSubsequences( nums,i+1 ); + path.removeLast(); + } + } +} +``` ### Python From fac4fc5193caac05a5418338f281e25c02a2739b Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 16 Feb 2022 23:22:26 +0800 Subject: [PATCH 141/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880617.?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E4=BA=8C=E5=8F=89=E6=A0=91.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/0617.合并二叉树.md | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index f815d741..55786ea9 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -583,6 +583,56 @@ var mergeTrees = function(root1, root2) { ``` +## TypeScript + +> 递归法: + +```type +function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 === null) return root2; + if (root2 === null) return root1; + const resNode: TreeNode = new TreeNode(root1.val + root2.val); + resNode.left = mergeTrees(root1.left, root2.left); + resNode.right = mergeTrees(root1.right, root2.right); + return resNode; +}; +``` + +> 迭代法: + +```typescript +function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null { + if (root1 === null) return root2; + if (root2 === null) return root1; + const helperQueue1: TreeNode[] = [], + helperQueue2: TreeNode[] = []; + helperQueue1.push(root1); + helperQueue2.push(root2); + let tempNode1: TreeNode, + tempNode2: TreeNode; + while (helperQueue1.length > 0) { + tempNode1 = helperQueue1.shift()!; + tempNode2 = helperQueue2.shift()!; + tempNode1.val += tempNode2.val; + if (tempNode1.left !== null && tempNode2.left !== null) { + helperQueue1.push(tempNode1.left); + helperQueue2.push(tempNode2.left); + } else if (tempNode1.left === null) { + tempNode1.left = tempNode2.left; + } + if (tempNode1.right !== null && tempNode2.right !== null) { + helperQueue1.push(tempNode1.right); + helperQueue2.push(tempNode2.right); + } else if (tempNode1.right === null) { + tempNode1.right = tempNode2.right; + } + } + return root1; +}; +``` + + + -----------------------

From bd2310622b8a4d726288759820a60b5a62fce590 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 17 Feb 2022 10:25:56 +0800 Subject: [PATCH 142/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880700.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E6=90=9C=E7=B4=A2.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0700.二叉搜索树中的搜索.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 1521514a..00ba8753 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -334,6 +334,36 @@ var searchBST = function (root, val) { }; ``` +## TypeScript + +> 递归法 + +```typescript +function searchBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null || root.val === val) return root; + if (root.val < val) return searchBST(root.right, val); + if (root.val > val) return searchBST(root.left, val); + return null; +}; +``` + +> 迭代法 + +```typescript +function searchBST(root: TreeNode | null, val: number): TreeNode | null { + let resNode: TreeNode | null = root; + while (resNode !== null) { + if (resNode.val === val) return resNode; + if (resNode.val < val) { + resNode = resNode.right; + } else { + resNode = resNode.left; + } + } + return null; +}; +``` + ----------------------- From 7af58b92b86e045998ce3f7ceca186d73809cbdd Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 17 Feb 2022 15:07:13 +0800 Subject: [PATCH 143/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880098.?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?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/0098.验证二叉搜索树.md | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 4ed29619..c0f3e039 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -526,6 +526,48 @@ var isValidBST = function (root) { }; ``` +## TypeScript + +> 辅助数组解决: + +```typescript +function isValidBST(root: TreeNode | null): boolean { + const traversalArr: number[] = []; + function inorderTraverse(root: TreeNode | null): void { + if (root === null) return; + inorderTraverse(root.left); + traversalArr.push(root.val); + inorderTraverse(root.right); + } + inorderTraverse(root); + for (let i = 0, length = traversalArr.length; i < length - 1; i++) { + if (traversalArr[i] >= traversalArr[i + 1]) return false; + } + return true; +}; +``` + +> 递归中解决: + +```typescript +function isValidBST(root: TreeNode | null): boolean { + let maxVal = -Infinity; + function inorderTraverse(root: TreeNode | null): boolean { + if (root === null) return true; + let leftValid: boolean = inorderTraverse(root.left); + if (!leftValid) return false; + if (maxVal < root.val) { + maxVal = root.val + } else { + return false; + } + let rightValid: boolean = inorderTraverse(root.right); + return leftValid && rightValid; + } + return inorderTraverse(root); +}; +``` + ----------------------- From 6cb2076827726fc5be341e226585882424e523e7 Mon Sep 17 00:00:00 2001 From: hs-zhangsan <1513157458@qq.com> Date: Fri, 18 Feb 2022 17:03:41 +0800 Subject: [PATCH 144/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20541.=E5=8F=8D?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2II=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 14b8601a..bf59f52d 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -98,8 +98,31 @@ public: ## 其他语言版本 +C: + +```c +char * reverseStr(char * s, int k){ + int len = strlen(s); + + for (int i = 0; i < len; i += (2 * k)) { + //判断剩余字符是否少于 k + k = i + k > len ? len - i : k; + + int left = i; + int right = i + k - 1; + while (left < right) { + char temp = s[left]; + s[left++] = s[right]; + s[right--] = temp; + } + } + + return s; +} +``` Java: + ```Java //解法一 class Solution { From 266702c291505ab3847d520ab7474789d0e97fab Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Fri, 18 Feb 2022 22:09:38 +0800 Subject: [PATCH 145/257] Update --- problems/前序/ACM模式如何构建二叉树.md | 3 --- problems/前序/BAT级别技术面试流程和注意事项都在这里了.md | 3 --- problems/前序/On的算法居然超时了,此时的n究竟是多大?.md | 3 --- problems/前序/上海互联网公司总结.md | 3 --- problems/前序/什么是核心代码模式,什么又是ACM模式?.md | 3 --- problems/前序/关于时间复杂度,你不知道的都在这里!.md | 3 --- problems/前序/关于空间复杂度,可能有几个疑问?.md | 3 --- problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md | 3 --- problems/前序/力扣上的代码想在本地编译运行?.md | 3 --- problems/前序/北京互联网公司总结.md | 3 --- problems/前序/广州互联网公司总结.md | 3 --- problems/前序/成都互联网公司总结.md | 3 --- problems/前序/杭州互联网公司总结.md | 3 --- problems/前序/深圳互联网公司总结.md | 3 --- problems/前序/程序员写文档工具.md | 3 --- problems/前序/程序员简历.md | 3 --- problems/前序/递归算法的时间与空间复杂度分析.md | 3 --- .../前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md | 3 --- 18 files changed, 54 deletions(-) diff --git a/problems/前序/ACM模式如何构建二叉树.md b/problems/前序/ACM模式如何构建二叉树.md index d3b2656e..fc7a1823 100644 --- a/problems/前序/ACM模式如何构建二叉树.md +++ b/problems/前序/ACM模式如何构建二叉树.md @@ -251,7 +251,4 @@ int main() { ``` ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md b/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md index c5797739..6678860d 100644 --- a/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md +++ b/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md @@ -218,7 +218,4 @@ leetcode是专门针对算法练习的题库,leetcode现在也推出了中文 ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md index 9a56937c..5257ceb9 100644 --- a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md @@ -280,7 +280,4 @@ public class TimeComplexity { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/上海互联网公司总结.md b/problems/前序/上海互联网公司总结.md index 08c15895..ffcbe77b 100644 --- a/problems/前序/上海互联网公司总结.md +++ b/problems/前序/上海互联网公司总结.md @@ -130,7 +130,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/什么是核心代码模式,什么又是ACM模式?.md b/problems/前序/什么是核心代码模式,什么又是ACM模式?.md index 3c5fb4e4..54c5b6ec 100644 --- a/problems/前序/什么是核心代码模式,什么又是ACM模式?.md +++ b/problems/前序/什么是核心代码模式,什么又是ACM模式?.md @@ -119,7 +119,4 @@ int main() { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/关于时间复杂度,你不知道的都在这里!.md b/problems/前序/关于时间复杂度,你不知道的都在这里!.md index cfcbed1a..478b82e4 100644 --- a/problems/前序/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/前序/关于时间复杂度,你不知道的都在这里!.md @@ -170,7 +170,4 @@ $O(2 × n^2 + 10 × n + 1000) < O(3 × n^2)$,所以说最后省略掉常数项 ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/关于空间复杂度,可能有几个疑问?.md b/problems/前序/关于空间复杂度,可能有几个疑问?.md index 95ffe597..d49b42a2 100644 --- a/problems/前序/关于空间复杂度,可能有几个疑问?.md +++ b/problems/前序/关于空间复杂度,可能有几个疑问?.md @@ -73,7 +73,4 @@ for (int i = 0; i < n; i++) { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md b/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md index 3fccfb22..0364fc8b 100644 --- a/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md +++ b/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md @@ -150,7 +150,4 @@ char型的数据和int型的数据挨在一起,该int数据从地址1开始, ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/力扣上的代码想在本地编译运行?.md b/problems/前序/力扣上的代码想在本地编译运行?.md index c4899a20..dca6eec3 100644 --- a/problems/前序/力扣上的代码想在本地编译运行?.md +++ b/problems/前序/力扣上的代码想在本地编译运行?.md @@ -67,7 +67,4 @@ int main() { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/北京互联网公司总结.md b/problems/前序/北京互联网公司总结.md index 0e22dad6..02a877b7 100644 --- a/problems/前序/北京互联网公司总结.md +++ b/problems/前序/北京互联网公司总结.md @@ -116,7 +116,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/广州互联网公司总结.md b/problems/前序/广州互联网公司总结.md index ae41c899..1cf0da36 100644 --- a/problems/前序/广州互联网公司总结.md +++ b/problems/前序/广州互联网公司总结.md @@ -79,7 +79,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/成都互联网公司总结.md b/problems/前序/成都互联网公司总结.md index d44800cd..7964f23c 100644 --- a/problems/前序/成都互联网公司总结.md +++ b/problems/前序/成都互联网公司总结.md @@ -77,7 +77,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/杭州互联网公司总结.md b/problems/前序/杭州互联网公司总结.md index 326a176b..029ee380 100644 --- a/problems/前序/杭州互联网公司总结.md +++ b/problems/前序/杭州互联网公司总结.md @@ -87,7 +87,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/深圳互联网公司总结.md b/problems/前序/深圳互联网公司总结.md index 9e089315..61bd52e8 100644 --- a/problems/前序/深圳互联网公司总结.md +++ b/problems/前序/深圳互联网公司总结.md @@ -82,7 +82,4 @@ ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/程序员写文档工具.md b/problems/前序/程序员写文档工具.md index e4193c42..5504ae7a 100644 --- a/problems/前序/程序员写文档工具.md +++ b/problems/前序/程序员写文档工具.md @@ -136,7 +136,4 @@ Markdown支持部分html,例如这样 ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/程序员简历.md b/problems/前序/程序员简历.md index f47516dc..522fc5f7 100644 --- a/problems/前序/程序员简历.md +++ b/problems/前序/程序员简历.md @@ -133,7 +133,4 @@ Carl校招社招都拿过大厂的offer,同时也看过很多应聘者的简 ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/递归算法的时间与空间复杂度分析.md b/problems/前序/递归算法的时间与空间复杂度分析.md index 4dd340a6..914cccfd 100644 --- a/problems/前序/递归算法的时间与空间复杂度分析.md +++ b/problems/前序/递归算法的时间与空间复杂度分析.md @@ -269,7 +269,4 @@ int binary_search( int arr[], int l, int r, int x) { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
diff --git a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md index 8780122f..849a025d 100644 --- a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md +++ b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md @@ -152,7 +152,4 @@ int function3(int x, int n) { ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
From f5fe6bd73c936faedc52b93de3cd56ec39c0ec84 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 18 Feb 2022 23:33:57 +0800 Subject: [PATCH 146/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88530.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E7=BB=9D=E5=AF=B9=E5=B7=AE=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/0530.二叉搜索树的最小绝对差.md | 71 ++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 3ebb4c8c..77699c9f 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -238,7 +238,7 @@ class Solution: cur = cur.right return result -``` +``` ## Go: @@ -364,5 +364,74 @@ var getMinimumDifference = function(root) { } ``` +## TypeScript + +> 辅助数组解决 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + let helperArr: number[] = []; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.left); + helperArr.push(root.val); + recur(root.right); + } + recur(root); + let resMin: number = Infinity; + for (let i = 0, length = helperArr.length; i < length - 1; i++) { + resMin = Math.min(resMin, helperArr[i + 1] - helperArr[i]); + } + return resMin; +}; +``` + +> 递归中解决 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + let preNode: TreeNode | null= null; + let resMin: number = Infinity; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.left); + if (preNode !== null) { + resMin = Math.min(resMin, root.val - preNode.val); + } + preNode = root; + recur(root.right); + } + recur(root); + return resMin; +}; +``` + +> 迭代法-中序遍历 + +```typescript +function getMinimumDifference(root: TreeNode | null): number { + const helperStack: TreeNode[] = []; + let curNode: TreeNode | null = root; + let resMin: number = Infinity; + let preNode: TreeNode | null = null; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + if (preNode !== null) { + resMin = Math.min(resMin, curNode.val - preNode.val); + } + preNode = curNode; + curNode = curNode.right; + } + } + return resMin; +}; +``` + + + -----------------------
From 28cff716ac11f9f5970593fb42a38b399eae9490 Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 11:52:30 +0800 Subject: [PATCH 147/257] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E9=80=92=E5=BD=92=E9=81=8D=E5=8E=86=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的递归遍历.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index c481fd11..9e131c6d 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -34,19 +34,19 @@ 1. **确定递归函数的参数和返回值**:因为要打印出前序遍历节点的数值,所以参数里需要传入vector在放节点的数值,除了这一点就不需要在处理什么数据了也不需要有返回值,所以递归函数返回类型就是void,代码如下: -``` +```cpp void traversal(TreeNode* cur, vector& vec) ``` 2. **确定终止条件**:在递归的过程中,如何算是递归结束了呢,当然是当前遍历的节点是空了,那么本层递归就要要结束了,所以如果当前遍历的这个节点是空,就直接return,代码如下: -``` +```cpp if (cur == NULL) return; ``` 3. **确定单层递归的逻辑**:前序遍历是中左右的循序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下: -``` +```cpp vec.push_back(cur->val); // 中 traversal(cur->left, vec); // 左 traversal(cur->right, vec); // 右 From a9ae0f5d03b4e6f819c3c3d518f2984cf54d8810 Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 11:55:45 +0800 Subject: [PATCH 148/257] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86=EF=BC=9A=E8=A1=A5=E5=85=85?= =?UTF-8?q?Swift=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/二叉树的迭代遍历.md --- problems/二叉树的迭代遍历.md | 104 +++++++++++++++-------------------- 1 file changed, 45 insertions(+), 59 deletions(-) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index ba38726b..8164724b 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -390,7 +390,7 @@ func inorderTraversal(root *TreeNode) []int { } ``` -javaScript +javaScript: ```js @@ -454,7 +454,7 @@ var postorderTraversal = function(root, res = []) { }; ``` -TypeScript: +TypeScript: ```typescript // 前序遍历(迭代法) @@ -509,77 +509,63 @@ function postorderTraversal(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: -> 迭代法前序遍历 ```swift +// 前序遍历迭代法 func preorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - stack.append(root!) + var result = [Int]() + guard let root = root else { return result } + var stack = [root] while !stack.isEmpty { - let node = stack.popLast()! - res.append(node.val) - if node.right != nil { - stack.append(node.right!) + let current = stack.removeLast() + // 先右后左,这样出栈的时候才是左右顺序 + if let node = current.right { // 右 + stack.append(node) } - if node.left != nil { - stack.append(node.left!) + if let node = current.left { // 左 + stack.append(node) } + result.append(current.val) // 中 } - return res + return result } -``` -> 迭代法中序遍历 -```swift -func inorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - var cur: TreeNode? = root - while cur != nil || !stack.isEmpty { - if cur != nil { - stack.append(cur!) - cur = cur!.left - } else { - cur = stack.popLast() - res.append(cur!.val) - cur = cur!.right - } - } - return res -} -``` - -> 迭代法后序遍历 -```swift +// 后序遍历迭代法 func postorderTraversal(_ root: TreeNode?) -> [Int] { - var res = [Int]() - if root == nil { - return res - } - var stack = [TreeNode]() - stack.append(root!) - // res 存储 中 -> 右 -> 左 + var result = [Int]() + guard let root = root else { return result } + var stack = [root] while !stack.isEmpty { - let node = stack.popLast()! - res.append(node.val) - if node.left != nil { - stack.append(node.left!) + let current = stack.removeLast() + // 与前序相反,即中右左,最后结果还需反转才是后序 + if let node = current.left { // 左 + stack.append(node) } - if node.right != nil { - stack.append(node.right!) + if let node = current.right { // 右 + stack.append(node) + } + result.append(current.val) // 中 + } + return result.reversed() +} + +// 中序遍历迭代法 +func inorderTraversal(_ root: TreeNode?) -> [Int] { + var result = [Int]() + var stack = [TreeNode]() + var current: TreeNode! = root + while current != nil || !stack.isEmpty { + if current != nil { // 先访问到最左叶子 + stack.append(current) + current = current.left // 左 + } else { + current = stack.removeLast() + result.append(current.val) // 中 + current = current.right // 右 } } - // res 翻转 - res.reverse() - return res + return result } ``` From af547486756b7213d17c10dd76c1a6e518a9b1fa Mon Sep 17 00:00:00 2001 From: bqlin Date: Tue, 21 Dec 2021 14:57:57 +0800 Subject: [PATCH 149/257] =?UTF-8?q?0102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=EF=BC=9A=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85Swift?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/0102.二叉树的层序遍历.md --- problems/0102.二叉树的层序遍历.md | 332 ++++++++++++++---------------- 1 file changed, 156 insertions(+), 176 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1a92d42f..8d6d2502 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -273,32 +273,29 @@ function levelOrder(root: TreeNode | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrder(_ root: TreeNode?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } - var queue = [TreeNode]() - queue.append(root) + var result = [[Int]]() + guard let root = root else { return result } + // 表示一层 + var queue = [root] while !queue.isEmpty { - let size = queue.count - var sub = [Int]() - for _ in 0 ..< size { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + subarray.append(node.val) + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(sub) + result.append(subarray) } - return res + + return result } ``` @@ -505,30 +502,29 @@ function levelOrderBottom(root: TreeNode | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } - var queue: [TreeNode] = [root] + // 表示一层 + var queue = [TreeNode]() + if let node = root { queue.append(node) } + var result = [[Int]]() while !queue.isEmpty { - var sub = [Int]() - for _ in 0 ..< queue.count { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + subarray.append(node.val) + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node)} } - res.insert(sub, at: 0) + result.append(subarray) } - return res + + return result.reversed() } ``` @@ -729,37 +725,31 @@ function rightSideView(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func rightSideView(_ root: TreeNode?) -> [Int] { - var res = [Int]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Int]() while !queue.isEmpty { - let size = queue.count - for i in 0 ..< size { + let count = queue.count + for i in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if i == size - 1 { - // 保存 每层最后一个元素 - res.append(node.val) - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + if i == count - 1 { result.append(node.val) } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } } - return res + + return result } ``` - # 637.二叉树的层平均值 [力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/) @@ -965,32 +955,30 @@ function averageOfLevels(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func averageOfLevels(_ root: TreeNode?) -> [Double] { - var res = [Double]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Double]() while !queue.isEmpty { - let size = queue.count + let count = queue.count var sum = 0 - for _ in 0 ..< size { + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() sum += node.val - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(Double(sum) / Double(size)) + result.append(Double(sum) / Double(count)) } - return res + + return result } ``` @@ -1212,29 +1200,28 @@ function levelOrder(root: Node | null): number[][] { }; ``` -Swift: +Swift: ```swift func levelOrder(_ root: Node?) -> [[Int]] { - var res = [[Int]]() - guard let root = root else { - return res - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [[Int]]() while !queue.isEmpty { - let size = queue.count - var sub = [Int]() - for _ in 0 ..< size { + let count = queue.count + var subarray = [Int]() + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - sub.append(node.val) - for childNode in node.children { - queue.append(childNode) - } + subarray.append(node.val) + // 下一层 + for node in node.children { queue.append(node) } } - res.append(sub) + result.append(subarray) } - return res + + return result } ``` @@ -1419,34 +1406,30 @@ function largestValues(root: TreeNode | null): number[] { }; ``` -Swift: +Swift: ```swift func largestValues(_ root: TreeNode?) -> [Int] { - var res = [Int]() - guard let root = root else { - return res - } + // 表示一层 var queue = [TreeNode]() - queue.append(root) + if let node = root { queue.append(node) } + var result = [Int]() while !queue.isEmpty { - let size = queue.count - var max: Int = Int.min - for _ in 0 ..< size { + let count = queue.count + var max = queue[0].val + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if node.val > max { - max = node.val - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + if node.val > max { max = node.val } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res.append(max) + result.append(max) } - return res + + return result } ``` @@ -1456,7 +1439,7 @@ func largestValues(_ root: TreeNode?) -> [Int] { 给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: -``` +```cpp struct Node { int val; Node *left; @@ -1677,33 +1660,34 @@ func connect(root *Node) *Node { } ``` -Swift: +Swift: + ```swift func connect(_ root: Node?) -> Node? { - guard let root = root else { - return nil - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } while !queue.isEmpty { - let size = queue.count - var preNode: Node? - for i in 0 ..< size { - let node = queue.removeFirst() + let count = queue.count + var current, previous: Node! + for i in 0 ..< count { + // 当前层 if i == 0 { - preNode = node + previous = queue.removeFirst() + current = previous } else { - preNode?.next = node - preNode = node - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + current = queue.removeFirst() + previous.next = current + previous = current } + + // 下一层 + if let node = current.left { queue.append(node) } + if let node = current.right { queue.append(node) } } + previous.next = nil } + return root } ``` @@ -1927,34 +1911,34 @@ func connect(root *Node) *Node { return root } ``` - Swift: + ```swift func connect(_ root: Node?) -> Node? { - guard let root = root else { - return nil - } + // 表示一层 var queue = [Node]() - queue.append(root) + if let node = root { queue.append(node) } while !queue.isEmpty { - let size = queue.count - var preNode: Node? - for i in 0 ..< size { - let node = queue.removeFirst() + let count = queue.count + var current, previous: Node! + for i in 0 ..< count { + // 当前层 if i == 0 { - preNode = node + previous = queue.removeFirst() + current = previous } else { - preNode?.next = node - preNode = node - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + current = queue.removeFirst() + previous.next = current + previous = current } + + // 下一层 + if let node = current.left { queue.append(node) } + if let node = current.right { queue.append(node) } } + previous.next = nil } + return root } ``` @@ -2151,29 +2135,28 @@ function maxDepth(root: TreeNode | null): number { }; ``` -Swift: +Swift: ```swift func maxDepth(_ root: TreeNode?) -> Int { - guard let root = root else { - return 0 - } + guard root != nil else { return 0 } + var depth = 0 var queue = [TreeNode]() - queue.append(root) - var res: Int = 0 + queue.append(root!) while !queue.isEmpty { - for _ in 0 ..< queue.count { + let count = queue.count + depth += 1 + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) - } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } - res += 1 } - return res + + return depth } ``` @@ -2374,28 +2357,25 @@ Swift: ```swift func minDepth(_ root: TreeNode?) -> Int { - guard let root = root else { - return 0 - } - var res = 0 - var queue = [TreeNode]() - queue.append(root) + guard root != nil else { return 0 } + var depth = 0 + var queue = [root!] while !queue.isEmpty { - res += 1 - for _ in 0 ..< queue.count { + let count = queue.count + depth += 1 + for _ in 0 ..< count { + // 当前层 let node = queue.removeFirst() - if node.left == nil && node.right == nil { - return res - } - if let left = node.left { - queue.append(left) - } - if let right = node.right { - queue.append(right) + if node.left == nil, node.right == nil { // 遇到叶子结点则返回 + return depth } + + // 下一层 + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } } } - return res + return depth } ``` From 53d4999ad8e7b16a790a8cfcdb6a0f030ec96dfd Mon Sep 17 00:00:00 2001 From: bqlin Date: Sat, 25 Dec 2021 17:14:15 +0800 Subject: [PATCH 150/257] =?UTF-8?q?0226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=EF=BC=9A=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E5=85=85Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Conflicts: # problems/0226.翻转二叉树.md --- problems/0226.翻转二叉树.md | 63 +++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 8108e7ad..a3ebe24d 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -47,8 +47,6 @@ ## 递归法 - - 对于二叉树的递归法的前中后序遍历,已经在[二叉树:前中后序递归遍历](https://programmercarl.com/二叉树的递归遍历.html)详细讲解了。 我们下文以前序遍历为例,通过动画来看一下翻转的过程: @@ -63,7 +61,7 @@ 返回值的话其实也不需要,但是题目中给出的要返回root节点的指针,可以直接使用题目定义好的函数,所以就函数的返回类型为`TreeNode*`。 -``` +```cpp TreeNode* invertTree(TreeNode* root) ``` @@ -71,7 +69,7 @@ TreeNode* invertTree(TreeNode* root) 当前节点为空的时候,就返回 -``` +```cpp if (root == NULL) return root; ``` @@ -79,7 +77,7 @@ if (root == NULL) return root; 因为是先前序遍历,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。 -``` +```cpp swap(root->left, root->right); invertTree(root->left); invertTree(root->right); @@ -257,7 +255,7 @@ public: ## 其他语言版本 -### Java: +### Java ```Java //DFS递归 @@ -469,8 +467,6 @@ func invertTree(root *TreeNode) *TreeNode { } ``` - - ### JavaScript 使用递归版本的前序遍历 @@ -690,7 +686,7 @@ function invertTree(root: TreeNode | null): TreeNode | null { }; ``` -### C: +### C 递归法 ```c @@ -775,5 +771,54 @@ func invertTree1(_ root: TreeNode?) -> TreeNode? { } ``` +### Swift + +深度优先递归。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + swap(&node.left, &node.right) + _ = invertTree(node.left) + _ = invertTree(node.right) + return root +} +``` + +深度优先迭代,子结点顺序不重要,从根结点出发深度遍历即可。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + var stack = [node] + while !stack.isEmpty { + guard let node = stack.popLast() else { break } + swap(&node.left, &node.right) + if let node = node.left { stack.append(node) } + if let node = node.right { stack.append(node) } + } + return root +} +``` + +广度优先迭代。 + +```swift +func invertTree(_ root: TreeNode?) -> TreeNode? { + guard let node = root else { return root } + var queue = [node] + while !queue.isEmpty { + let count = queue.count + for _ in 0 ..< count { + let node = queue.removeFirst() + swap(&node.left, &node.right) + if let node = node.left { queue.append(node) } + if let node = node.right { queue.append(node) } + } + } + return root +} +``` + -----------------------
From 9b991d89948d5793f1f93cedb7d0c2093586506e Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 19 Feb 2022 15:05:26 +0800 Subject: [PATCH 151/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880501.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E4=BC=97=E6=95=B0.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 105 +++++++++++++++++++++++++++- 1 file changed, 103 insertions(+), 2 deletions(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 277f46f5..1be9ee6a 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -512,7 +512,7 @@ class Solution: self.search_BST(cur.right) ``` - + > 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性 ```python3 @@ -661,7 +661,7 @@ var findMode = function(root) { } return res; }; -``` +``` 不使用额外空间,利用二叉树性质,中序遍历(有序): @@ -699,6 +699,107 @@ var findMode = function(root) { }; ``` +## TypeScript + +> 辅助Map法 + +```typescript +function findMode(root: TreeNode | null): number[] { + if (root === null) return []; + const countMap: Map = new Map(); + function traverse(root: TreeNode | null): void { + if (root === null) return; + countMap.set(root.val, (countMap.get(root.val) || 0) + 1); + traverse(root.left); + traverse(root.right); + } + traverse(root); + const countArr: number[][] = Array.from(countMap); + countArr.sort((a, b) => { + return b[1] - a[1]; + }) + const resArr: number[] = []; + const maxCount: number = countArr[0][1]; + for (let i of countArr) { + if (i[1] === maxCount) resArr.push(i[0]); + } + return resArr; +}; +``` + +> 递归中直接解决 + +```typescript +function findMode(root: TreeNode | null): number[] { + let preNode: TreeNode | null = null; + let maxCount: number = 0; + let count: number = 0; + let resArr: number[] = []; + function traverse(root: TreeNode | null): void { + if (root === null) return; + traverse(root.left); + if (preNode === null) { // 第一个节点 + count = 1; + } else if (preNode.val === root.val) { + count++; + } else { + count = 1; + } + if (count === maxCount) { + resArr.push(root.val); + } else if (count > maxCount) { + maxCount = count; + resArr.length = 0; + resArr.push(root.val); + } + preNode = root; + traverse(root.right); + } + traverse(root); + return resArr; +}; +``` + +> 迭代法 + +```typescript +function findMode(root: TreeNode | null): number[] { + const helperStack: TreeNode[] = []; + const resArr: number[] = []; + let maxCount: number = 0; + let count: number = 0; + let preNode: TreeNode | null = null; + let curNode: TreeNode | null = root; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + if (preNode === null) { // 第一个节点 + count = 1; + } else if (preNode.val === curNode.val) { + count++; + } else { + count = 1; + } + if (count === maxCount) { + resArr.push(curNode.val); + } else if (count > maxCount) { + maxCount = count; + resArr.length = 0; + resArr.push(curNode.val); + } + preNode = curNode; + curNode = curNode.right; + } + } + return resArr; +}; +``` + + + -----------------------
From 292fe1eb380622ce4fc19f2d05ef26bb472e855d Mon Sep 17 00:00:00 2001 From: hs-zhangsan <1513157458@qq.com> Date: Sat, 19 Feb 2022 15:55:31 +0800 Subject: [PATCH 152/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=91=E6=8C=87?= =?UTF-8?q?Offer=2005.=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 530545fb..9e743887 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -121,6 +121,37 @@ for (int i = 0; i < a.size(); i++) { ## 其他语言版本 +C: +```C +char* replaceSpace(char* s){ + //统计空格数量 + int count = 0; + int len = strlen(s); + for (int i = 0; i < len; i++) { + if (s[i] == ' ') { + count++; + } + } + + //为新数组分配空间 + int newLen = len + count * 2; + char* result = malloc(sizeof(char) * newLen + 1); + //填充新数组并替换空格 + for (int i = len - 1, j = newLen - 1; i >= 0; i--, j--) { + if (s[i] != ' ') { + result[j] = s[i]; + } else { + result[j--] = '0'; + result[j--] = '2'; + result[j] = '%'; + } + } + result[newLen] = '\0'; + + return result; +} +``` + Java: ```Java From bb277e08e19b797a1b5da5bfe0c60ef84b5c9c8e Mon Sep 17 00:00:00 2001 From: K-945 <393763635@qq.com> Date: Sun, 20 Feb 2022 17:56:21 +0800 Subject: [PATCH 153/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00059.=E8=9E=BA?= =?UTF-8?q?=E6=97=8B=E7=9F=A9=E9=98=B5II.md=20=E5=92=8C=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E7=9B=B8=E5=90=8C=E7=9A=84python=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0059.螺旋矩阵II.md | 60 ++++++++++++++----------------------- 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 3f7a59ca..a98e72ad 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -192,47 +192,31 @@ python: ```python3 class Solution: - def generateMatrix(self, n: int) -> List[List[int]]: - # 初始化要填充的正方形 - matrix = [[0] * n for _ in range(n)] + nums = [[0] * n for _ in range(n)] + startx, starty = 0, 0 # 起始点 + loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点 + count = 1 # 计数 - left, right, up, down = 0, n - 1, 0, n - 1 - number = 1 # 要填充的数字 + for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从1开始 + for i in range(starty, n - offset) : # 从左至右,左闭右开 + nums[startx][i] = count + count += 1 + for i in range(startx, n - offset) : # 从上至下 + nums[i][n - offset] = count + count += 1 + for i in range(n - offset, starty, -1) : # 从右至左 + nums[n - offset][i] = count + count += 1 + for i in range(n - offset, startx, -1) : # 从下至上 + nums[i][starty] = count + count += 1 + startx += 1 # 更新起始点 + starty += 1 - while left < right and up < down: - - # 从左到右填充上边 - for x in range(left, right): - matrix[up][x] = number - number += 1 - - # 从上到下填充右边 - for y in range(up, down): - matrix[y][right] = number - number += 1 - - # 从右到左填充下边 - for x in range(right, left, -1): - matrix[down][x] = number - number += 1 - - # 从下到上填充左边 - for y in range(down, up, -1): - matrix[y][left] = number - number += 1 - - # 缩小要填充的范围 - left += 1 - right -= 1 - up += 1 - down -= 1 - - # 如果阶数为奇数,额外填充一次中心 - if n % 2: - matrix[n // 2][n // 2] = number - - return matrix + if n % 2 != 0 : # n为奇数时,填充中心点 + nums[mid][mid] = count + return nums ``` javaScript From ceaaa2fd2d3114c75794b89fbb08005dd991b81c Mon Sep 17 00:00:00 2001 From: Epoch <75031971+messenger1th@users.noreply.github.com> Date: Mon, 21 Feb 2022 14:37:15 +0800 Subject: [PATCH 154/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200151.=E7=BF=BB?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95?= =?UTF-8?q?=E8=AF=8D=E7=9A=84CPP=E6=9B=B4=E7=AE=80=E6=B4=81=E7=9A=84?= =?UTF-8?q?=E7=89=88=E6=9C=AC2=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用LC27的原理使得更为简洁。 --- problems/0151.翻转字符串里的单词.md | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index ead5fa12..677a8f64 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -222,7 +222,42 @@ public: 效率: +```CPP +//版本二: +class Solution { +public: + void reverseWord(string& s,int start,int end){ //这个函数,Carl哥的要更清晰。 + for(int i=start;i<(end-start)/2+start;++i){ + swap(s[i],s[end-1-i+start]); + } + } + void trim(string& s){//去除所有空格并在相邻单词之间添加空格 + int slow = 0; + for(int i=0;i Date: Thu, 24 Feb 2022 00:36:23 +0800 Subject: [PATCH 155/257] Added in one more python solution. Using defaultdict. --- problems/0454.四数相加II.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index a7c903eb..a6cd413b 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -141,7 +141,24 @@ class Solution(object): ``` +```python +class Solution: + def fourSumCount(self, nums1: list, nums2: list, nums3: list, nums4: list) -> int: + from collections import defaultdict # You may use normal dict instead. + rec, cnt = defaultdict(lambda : 0), 0 + # To store the summary of all the possible combinations of nums1 & nums2, together with their frequencies. + for i in nums1: + for j in nums2: + rec[i+j] += 1 + # To add up the frequencies if the corresponding value occurs in the dictionary + for i in nums3: + for j in nums4: + cnt += rec.get(-(i+j), 0) # No matched key, return 0. + return cnt +``` + Go: + ```go func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int { m := make(map[int]int) From 3652d00e542fc251d479a66eb676c8e1ac910f45 Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Thu, 24 Feb 2022 17:49:15 +0800 Subject: [PATCH 156/257] =?UTF-8?q?0104=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6=20=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=B9=A6=E5=86=99=E9=94=99=E8=AF=AF=E7=BA=A0?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 函数错误,逻辑错误 --- problems/0104.二叉树的最大深度.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 3eecdc92..2229a854 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -523,8 +523,8 @@ func maxdepth(root *treenode) int { ```javascript var maxdepth = function(root) { - if (!root) return root - return 1 + math.max(maxdepth(root.left), maxdepth(root.right)) + if (root === null) return 0; + return 1 + Math.max(maxdepth(root.left), maxdepth(root.right)) }; ``` @@ -541,7 +541,7 @@ var maxdepth = function(root) { //3. 确定单层逻辑 let leftdepth=getdepth(node.left); let rightdepth=getdepth(node.right); - let depth=1+math.max(leftdepth,rightdepth); + let depth=1+Math.max(leftdepth,rightdepth); return depth; } return getdepth(root); @@ -591,7 +591,9 @@ var maxDepth = function(root) { count++ while(size--) { let node = queue.shift() - node && (queue = [...queue, ...node.children]) + for (let item of node.children) { + item && queue.push(item); + } } } return count From 5b78393ac4e70db5cf9518090f4cb563c68e11d6 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Fri, 25 Feb 2022 00:57:43 +0800 Subject: [PATCH 157/257] modified 15. Add a new version with the same idea. --- problems/0015.三数之和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index e191eabc..1d811b76 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -243,7 +243,34 @@ class Solution: right -= 1 return ans ``` +Python (v2): + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if len(nums) < 3: return [] + nums, res = sorted(nums), [] + for i in range(len(nums) - 2): + cur, l, r = nums[i], i + 1, len(nums) - 1 + if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time. + + while l < r: + if cur + nums[l] + nums[r] == 0: + res.append([cur, nums[l], nums[r]]) + # Drop duplicates for the second time in interation of l & r. Only used when target situation occurs, because that is the reason for dropping duplicates. + while l < r - 1 and nums[l] == nums[l + 1]: + l += 1 + while r > l + 1 and nums[r] == nums[r - 1]: + r -= 1 + if cur + nums[l] + nums[r] > 0: + r -= 1 + else: + l += 1 + return res +``` + Go: + ```Go func threeSum(nums []int)[][]int{ sort.Ints(nums) From 14f91a53702d8df5e1a587e757f739b5df55bb8f Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Fri, 25 Feb 2022 10:37:17 +0800 Subject: [PATCH 158/257] =?UTF-8?q?0404=20=E5=B7=A6=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20=20=E5=B7=A6=E5=8F=B6=E5=AD=90=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0404.左叶子之和.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 09272052..691c0f37 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -19,7 +19,7 @@ **首先要注意是判断左叶子,不是二叉树左侧节点,所以不要上来想着层序遍历。** -因为题目中其实没有说清楚左叶子究竟是什么节点,那么我来给出左叶子的明确定义:**如果左节点不为空,且左节点没有左右孩子,那么这个节点就是左叶子** +因为题目中其实没有说清楚左叶子究竟是什么节点,那么我来给出左叶子的明确定义:**如果左节点不为空,且左节点没有左右孩子,那么这个节点的左节点就是左叶子** 大家思考一下如下图中二叉树,左叶子之和究竟是多少? From 984a3ae5bc7d08bb70b05601d96d57b1b0c9c791 Mon Sep 17 00:00:00 2001 From: cylin2000 Date: Fri, 25 Feb 2022 10:56:23 +0000 Subject: [PATCH 159/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE=20C#=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0704.二分查找.md | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 379cb5fc..635868a9 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -561,5 +561,51 @@ class Solution { } ``` +**C#** +```csharp +//左闭右闭 +public class Solution { + public int Search(int[] nums, int target) { + int left = 0; + int right = nums.Length - 1; + while(left <= right){ + int mid = (right - left ) / 2 + left; + if(nums[mid] == target){ + return mid; + } + else if(nums[mid] < target){ + left = mid+1; + } + else if(nums[mid] > target){ + right = mid-1; + } + } + return -1; + } +} + +//左闭右开 +public class Solution{ + public int Search(int[] nums, int target){ + int left = 0; + int right = nums.Length; + while(left < right){ + int mid = (right - left) / 2 + left; + if(nums[mid] == target){ + return mid; + } + else if(nums[mid] < target){ + left = mid + 1; + } + else if(nums[mid] > target){ + right = mid; + } + } + return -1; + } +} +``` + + -----------------------
From 3f189d4687818313a90bc240524a3dc049f39ec4 Mon Sep 17 00:00:00 2001 From: cylin2000 Date: Fri, 25 Feb 2022 10:57:05 +0000 Subject: [PATCH 160/257] Add : --- problems/0704.二分查找.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 635868a9..15e096a0 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -561,7 +561,7 @@ class Solution { } ``` -**C#** +**C#:** ```csharp //左闭右闭 public class Solution { From 4980496c05aad48ea28cc0ed471cc08ffe36b9d6 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Fri, 25 Feb 2022 18:59:56 +0800 Subject: [PATCH 161/257] 0001. Add python v2. Making use of the dictionary property. --- problems/0001.两数之和.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 22b2e7eb..9571a773 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -118,6 +118,18 @@ class Solution: return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引 ``` +Python (v2): + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + rec = {} + for i in range(len(nums)): + rest = target - nums[i] + # Use get to get the index of the data, making use of one of the dictionary properties. + if rec.get(rest, None) is not None: return [rec[rest], i] + rec[nums[i]] = i +``` Go: From 0738423c9ed3979fa649ba7a147c4c60ecdec616 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 00:24:13 +0800 Subject: [PATCH 162/257] modified 541. Can be more pythonic. --- problems/0541.反转字符串II.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 14b8601a..cd9bb0cc 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -204,8 +204,23 @@ class Solution: return ''.join(res) ``` +Python3 (v2): + +```python +class Solution: + def reverseStr(self, s: str, k: int) -> str: + # Two pointers. Another is inside the loop. + p = 0 + while p < len(s): + p2 = p + k + # Written in this could be more pythonic. + s = s[:p] + s[p: p2][::-1] + s[p2:] + p = p + 2 * k + return s +``` Go: + ```go func reverseStr(s string, k int) string { ss := []byte(s) From f862ebf0c70c37c62f83b5ad50b441c830f5850f Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 00:41:18 +0800 Subject: [PATCH 163/257] modified offer05. Add two python versions. --- problems/剑指Offer05.替换空格.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 530545fb..59f74a18 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -260,8 +260,24 @@ class Solution: ``` +```python +class Solution: + def replaceSpace(self, s: str) -> str: + # method 1 - Very rude + return "%20".join(s.split(" ")) + + # method 2 - Reverse the s when counting in for loop, then update from the end. + n = len(s) + for e, i in enumerate(s[::-1]): + print(i, e) + if i == " ": + s = s[: n - (e + 1)] + "%20" + s[n - e:] + print("") + return s +``` javaScript: + ```js /** * @param {string} s From 0fbacd5d9b4c72db15f5f1ddae2c73b320a8c554 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Sun, 27 Feb 2022 01:19:55 +0800 Subject: [PATCH 164/257] modified 151. Add 2 python versions. No need to implement Carlo's idea in such a complecated way by inviting extra space. --- problems/0151.翻转字符串里的单词.md | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index ead5fa12..7588cbd6 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -438,6 +438,38 @@ class Solution: ``` +```python +class Solution: + def reverseWords(self, s: str) -> str: + # method 1 - Rude but work & efficient method. + s_list = [i for i in s.split(" ") if len(i) > 0] + return " ".join(s_list[::-1]) + + # method 2 - Carlo's idea + def trim_head_tail_space(ss: str): + p = 0 + while p < len(ss) and ss[p] == " ": + p += 1 + return ss[p:] + + # Trim the head and tail space + s = trim_head_tail_space(s) + s = trim_head_tail_space(s[::-1])[::-1] + + pf, ps, s = 0, 0, s[::-1] # Reverse the string. + while pf < len(s): + if s[pf] == " ": + # Will not excede. Because we have clean the tail space. + if s[pf] == s[pf + 1]: + s = s[:pf] + s[pf + 1:] + continue + else: + s = s[:ps] + s[ps: pf][::-1] + s[pf:] + ps, pf = pf + 1, pf + 2 + else: + pf += 1 + return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions, +``` Go: From ef747f7921ccd6b64a6de661847eac88528bbb40 Mon Sep 17 00:00:00 2001 From: Qiyu Liang <61932152+Guicai996@users.noreply.github.com> Date: Sun, 27 Feb 2022 19:57:40 +0800 Subject: [PATCH 165/257] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改了L48-54,增选解释了一种特殊情况:节点本身p(q),它拥有一个子孙节点q(p)。 --- problems/0236.二叉树的最近公共祖先.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 6213aeaa..5b2abd18 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -45,9 +45,13 @@ 接下来就看如何判断一个节点是节点q和节点p的公共公共祖先呢。 -**如果找到一个节点,发现左子树出现结点p,右子树出现节点q,或者 左子树出现结点q,右子树出现节点p,那么该节点就是节点p和q的最近公共祖先。** +**首先最容易想到的一个情况:如果找到一个节点,发现左子树出现结点p,右子树出现节点q,或者 左子树出现结点q,右子树出现节点p,那么该节点就是节点p和q的最近公共祖先。** -使用后序遍历,回溯的过程,就是从低向上遍历节点,一旦发现如何这个条件的节点,就是最近公共节点了。 +**但是很多人容易忽略一个情况,就是节点本身p(q),它拥有一个子孙节点q(p)。** + +使用后序遍历,回溯的过程,就是从低向上遍历节点,一旦发现满足第一种情况的节点,就是最近公共节点了。 + +**但是如果p或者q本身就是最近公共祖先呢?其实只需要找到一个节点是p或者q的时候,直接返回当前节点,无需继续递归子树。如果接下来的遍历中找到了后继节点满足第一种情况则修改返回值为后继节点,否则,继续返回已找到的节点即可。为什么满足第一种情况的节点一定是p或q的后继节点呢?大家可以仔细思考一下。** 递归三部曲: From 9712e3f75cbd0525eb40e0d12c264d1aa1952ea6 Mon Sep 17 00:00:00 2001 From: jinyuhang-007 <53509988+jinyuhang-007@users.noreply.github.com> Date: Sun, 27 Feb 2022 17:35:50 -0800 Subject: [PATCH 166/257] =?UTF-8?q?=E6=9B=B4=E6=96=B00005.=E6=9C=80?= =?UTF-8?q?=E9=95=BF=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0005.最长回文子串.md | 37 +++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 99458825..8b3af3bb 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -260,7 +260,26 @@ public: # 其他语言版本 -## Java +Java: + +```java +public int[] twoSum(int[] nums, int target) { + int[] res = new int[2]; + if(nums == null || nums.length == 0){ + return res; + } + Map map = new HashMap<>(); + for(int i = 0; i < nums.length; i++){ + int temp = target - nums[i]; + if(map.containsKey(temp)){ + res[1] = i; + res[0] = map.get(temp); + } + map.put(nums[i], i); + } + return res; +} +``` ```java // 双指针 中心扩散法 @@ -291,7 +310,7 @@ class Solution { } ``` -## Python +Python: ```python class Solution: @@ -312,7 +331,8 @@ class Solution: return s[left:right + 1] ``` -> 双指针法: +双指针: + ```python class Solution: def longestPalindrome(self, s: str) -> str: @@ -340,13 +360,13 @@ class Solution: return s[start:end] ``` -## Go +Go: ```go ``` -## JavaScript +JavaScript: ```js //动态规划解法 @@ -462,8 +482,9 @@ var longestPalindrome = function(s) { }; ``` -## C -动态规划: +C: + +动态规划: ```c //初始化dp数组,全部初始为false bool **initDP(int strLen) { @@ -513,7 +534,7 @@ char * longestPalindrome(char * s){ } ``` -双指针: +双指针: ```c int left, maxLength; void extend(char *str, int i, int j, int size) { From ee0e80dae79071d1b48dfcc022e33f827de9c532 Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Mon, 28 Feb 2022 14:18:29 +0800 Subject: [PATCH 167/257] =?UTF-8?q?0700=20=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=20=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=9B=B4=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 结果没问题,但逻辑不严谨 --- problems/0700.二叉搜索树中的搜索.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 1521514a..fd1d21ac 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -200,7 +200,7 @@ class Solution { if (val < root.val) root = root.left; else if (val > root.val) root = root.right; else return root; - return root; + return null; } } ``` @@ -236,7 +236,7 @@ class Solution: if val < root.val: root = root.left elif val > root.val: root = root.right else: return root - return root + return None ``` @@ -271,7 +271,7 @@ func searchBST(root *TreeNode, val int) *TreeNode { break } } - return root + return nil } ``` @@ -301,7 +301,6 @@ var searchBST = function (root, val) { return searchBST(root.left, val); if (root.val < val) return searchBST(root.right, val); - return null; }; ``` @@ -330,7 +329,7 @@ var searchBST = function (root, val) { else return root; } - return root; + return null; }; ``` From 32dada4f6d071c10643dd69c356aeba74601cf21 Mon Sep 17 00:00:00 2001 From: Qiyu Liang <61932152+Guicai996@users.noreply.github.com> Date: Mon, 28 Feb 2022 15:01:23 +0800 Subject: [PATCH 168/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200063.=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E8=B7=AF=E5=BE=84II=E5=A2=9E=E5=8A=A0=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E4=BC=98=E5=8C=96=E7=89=88=E6=9C=ACc++=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0063.不同路径II,L159-190 增加空间优化版本c++代码 --- problems/0063.不同路径II.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 8e82007e..86c42150 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -155,6 +155,39 @@ public: * 时间复杂度:$O(n × m)$,n、m 分别为obstacleGrid 长度和宽度 * 空间复杂度:$O(n × m)$ + +同样我们给出空间优化版本: +```CPP +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + if (obstacleGrid[0][0] == 1) + return 0; + vector dp(obstacleGrid[0].size()); + for (int j = 0; j < dp.size(); ++j) + if (obstacleGrid[0][j] == 1) + dp[j] = 0; + else if (j == 0) + dp[j] = 1; + else + dp[j] = dp[j-1]; + + for (int i = 1; i < obstacleGrid.size(); ++i) + for (int j = 0; j < dp.size(); ++j){ + if (obstacleGrid[i][j] == 1) + dp[j] = 0; + else if (j != 0) + dp[j] = dp[j] + dp[j-1]; + } + return dp.back(); + } +}; +``` + +* 时间复杂度:$O(n × m)$,n、m 分别为obstacleGrid 长度和宽度 +* 空间复杂度:$O(m)$ + + ## 总结 本题是[62.不同路径](https://programmercarl.com/0062.不同路径.html)的障碍版,整体思路大体一致。 From 37e7d73ec200bd9adefbdaaef24d6f4c2e38f5f7 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Mon, 28 Feb 2022 20:52:01 +0800 Subject: [PATCH 169/257] Update --- problems/0020.有效的括号.md | 4 ++-- problems/0027.移除元素.md | 2 +- problems/0035.搜索插入位置.md | 2 +- problems/0039.组合总和.md | 4 ++-- problems/0040.组合总和II.md | 4 ++-- problems/0042.接雨水.md | 2 +- problems/0046.全排列.md | 2 +- problems/0059.螺旋矩阵II.md | 4 ++-- problems/0070.爬楼梯完全背包版本.md | 4 ++-- problems/0077.组合优化.md | 2 +- problems/0078.子集.md | 2 +- problems/0084.柱状图中最大的矩形.md | 4 ++-- problems/0093.复原IP地址.md | 2 +- problems/0102.二叉树的层序遍历.md | 4 ++-- problems/0108.将有序数组转换为二叉搜索树.md | 2 +- problems/0110.平衡二叉树.md | 2 +- problems/0129.求根到叶子节点数字之和.md | 2 +- problems/0131.分割回文串.md | 4 ++-- problems/0188.买卖股票的最佳时机IV.md | 2 +- problems/0257.二叉树的所有路径.md | 2 +- problems/0279.完全平方数.md | 2 +- problems/0322.零钱兑换.md | 2 +- problems/0337.打家劫舍III.md | 6 +++--- problems/0376.摆动序列.md | 2 +- problems/0383.赎金信.md | 2 +- problems/0404.左叶子之和.md | 4 ++-- problems/0455.分发饼干.md | 2 +- problems/0463.岛屿的周长.md | 2 +- problems/0474.一和零.md | 2 +- problems/0491.递增子序列.md | 4 ++-- problems/0494.目标和.md | 11 ++++++++--- problems/0496.下一个更大元素I.md | 4 ++-- problems/0501.二叉搜索树中的众数.md | 4 ++-- problems/0503.下一个更大元素II.md | 2 +- problems/0518.零钱兑换II.md | 2 +- problems/0538.把二叉搜索树转换为累加树.md | 2 +- problems/0669.修剪二叉搜索树.md | 2 +- problems/0841.钥匙和房间.md | 1 - problems/1047.删除字符串中的所有相邻重复项.md | 4 ++-- problems/二叉树的递归遍历.md | 2 +- problems/周总结/20201003二叉树周末总结.md | 4 ++-- problems/背包问题理论基础完全背包.md | 2 +- 42 files changed, 64 insertions(+), 60 deletions(-) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 95d62e42..01fc7b93 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -159,7 +159,7 @@ class Solution { ``` Python: -```python3 +```python # 方法一,仅使用栈,更省空间 class Solution: def isValid(self, s: str) -> bool: @@ -180,7 +180,7 @@ class Solution: return True if not stack else False ``` -```python3 +```python # 方法二,使用字典 class Solution: def isValid(self, s: str) -> bool: diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index d69f2bcf..dd9155c6 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -142,7 +142,7 @@ class Solution { Python: -```python3 +```python class Solution: """双指针法 时间复杂度:O(n) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index f5f041aa..9a770703 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -246,7 +246,7 @@ func searchInsert(nums []int, target int) int { ``` ### Python -```python3 +```python class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left, right = 0, len(nums) - 1 diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index 0f8fe4f6..7a2084dd 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -264,7 +264,7 @@ class Solution { ## Python **回溯** -```python3 +```python class Solution: def __init__(self): self.path = [] @@ -296,7 +296,7 @@ class Solution: self.path.pop() # 回溯 ``` **剪枝回溯** -```python3 +```python class Solution: def __init__(self): self.path = [] diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 54384188..49acb8d6 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -334,7 +334,7 @@ class Solution { ## Python **回溯+巧妙去重(省去使用used** -```python3 +```python class Solution: def __init__(self): self.paths = [] @@ -374,7 +374,7 @@ class Solution: sum_ -= candidates[i] # 回溯,为了下一轮for loop ``` **回溯+去重(使用used)** -```python3 +```python class Solution: def __init__(self): self.paths = [] diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index 27745607..55f80a54 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -491,7 +491,7 @@ class Solution: return res ``` 动态规划 -```python3 +```python class Solution: def trap(self, height: List[int]) -> int: leftheight, rightheight = [0]*len(height), [0]*len(height) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 3d31db62..c5369ddd 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -243,7 +243,7 @@ class Solution: usage_list[i] = False ``` **回溯+丢掉usage_list** -```python3 +```python class Solution: def __init__(self): self.path = [] diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 3f7a59ca..670d6fc2 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -188,9 +188,9 @@ class Solution { } ``` -python: +python3: -```python3 +```python class Solution: def generateMatrix(self, n: int) -> List[List[int]]: diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index b5fbb96a..2286de2d 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -143,10 +143,10 @@ class Solution { } ``` -Python: +Python3: -```python3 +```python class Solution: def climbStairs(self, n: int) -> int: dp = [0]*(n + 1) diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index e995fd18..81b4304c 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -174,7 +174,7 @@ class Solution { ``` Python: -```python3 +```python class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res=[] #存放符合条件结果的集合 diff --git a/problems/0078.子集.md b/problems/0078.子集.md index 1abf8c95..cdb5f548 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -203,7 +203,7 @@ class Solution { ``` ## Python -```python3 +```python class Solution: def __init__(self): self.path: List[int] = [] diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index 3cb51f1d..439a3bc5 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -277,9 +277,9 @@ class Solution { } ``` -Python: +Python3: -```python3 +```python # 双指针;暴力解法(leetcode超时) class Solution: diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 3e7cd1ad..1fa72cc9 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -339,7 +339,7 @@ class Solution(object): ``` python3: -```python3 +```python class Solution: def __init__(self): self.result = [] diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 1a92d42f..74485848 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -83,10 +83,10 @@ public: }; ``` -python代码: +python3代码: -```python3 +```python class Solution: """二叉树层序遍历迭代解法""" diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index bd48ea0c..9e008e86 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -305,7 +305,7 @@ class Solution { ## Python **递归** -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 90cb7336..d9dcf289 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -497,7 +497,7 @@ class Solution { ## Python 递归法: -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index 980779c2..b271ca7d 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -217,7 +217,7 @@ class Solution { ``` Python: -```python3 +```python class Solution: def sumNumbers(self, root: TreeNode) -> int: res = 0 diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 439ad8ea..f50f1c1d 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -289,7 +289,7 @@ class Solution { ## Python **回溯+正反序判断回文串** -```python3 +```python class Solution: def __init__(self): self.paths = [] @@ -326,7 +326,7 @@ class Solution: continue ``` **回溯+函数判断回文串** -```python3 +```python class Solution: def __init__(self): self.paths = [] diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 7db75f06..61c558a1 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -271,7 +271,7 @@ class Solution: return dp[-1][2*k] ``` 版本二 -```python3 +```python class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: if len(prices) == 0: return 0 diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 4078320f..a0c718f4 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -436,7 +436,7 @@ class Solution: 迭代法: -```python3 +```python from collections import deque diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index 7bc0c2f7..9bad2085 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -207,7 +207,7 @@ class Solution { Python: -```python3 +```python class Solution: def numSquares(self, n: int) -> int: '''版本一,先遍历背包, 再遍历物品''' diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index 8f3438af..3a8d0662 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -207,7 +207,7 @@ class Solution { Python: -```python3 +```python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: '''版本一''' diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index 06831cb6..ecd31d1b 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -288,7 +288,7 @@ Python: > 暴力递归 -```python3 +```python # Definition for a binary tree node. # class TreeNode: @@ -315,7 +315,7 @@ class Solution: > 记忆化递归 -```python3 +```python # Definition for a binary tree node. # class TreeNode: @@ -345,7 +345,7 @@ class Solution: ``` > 动态规划 -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index d75311eb..5076c9ad 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -228,7 +228,7 @@ class Solution { ### Python -```python3 +```python class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: preC,curC,res = 0,0,1 #题目里nums长度大于等于1,当长度为1时,其实到不了for循环里去,所以不用考虑nums长度 diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 31e19b10..00707347 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -209,7 +209,7 @@ class Solution(object): Python写法四: -```python3 +```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: c1 = collections.Counter(ransomNote) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 09272052..8c6eaddb 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -229,7 +229,7 @@ class Solution { ## Python **递归后序遍历** -```python3 +```python class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: if not root: @@ -246,7 +246,7 @@ class Solution: ``` **迭代** -```python3 +```python class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: """ diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 1711f638..210b492d 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -146,7 +146,7 @@ class Solution { ``` ### Python -```python3 +```python class Solution: # 思路1:优先考虑胃饼干 def findContentChildren(self, g: List[int], s: List[int]) -> int: diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index e19e06ee..9911dfe5 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -124,7 +124,7 @@ Python: ### 解法1: 扫描每个cell,如果当前位置为岛屿 grid[i][j] == 1, 从当前位置判断四边方向,如果边界或者是水域,证明有边界存在,res矩阵的对应cell加一。 -```python3 +```python class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 67e366f4..964df4a8 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -193,7 +193,7 @@ class Solution { ``` Python: -```python3 +```python class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: dp = [[0] * (n + 1) for _ in range(m + 1)] # 默认初始化0 diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 6d88119e..70b08d50 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -233,7 +233,7 @@ class Solution { python3 **回溯** -```python3 +```python class Solution: def __init__(self): self.paths = [] @@ -270,7 +270,7 @@ class Solution: self.path.pop() ``` **回溯+哈希表去重** -```python3 +```python class Solution: def __init__(self): self.paths = [] diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index f190b734..47d0784e 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -160,11 +160,16 @@ dp[j] 表示:填满j(包括j)这么大容积的包,有dp[j]种方法 那么只要搞到nums[i]的话,凑成dp[j]就有dp[j - nums[i]] 种方法。 -举一个例子,nums[i] = 2: dp[3],填满背包容量为3的话,有dp[3]种方法。 -那么只需要搞到一个2(nums[i]),有dp[3]方法可以凑齐容量为3的背包,相应的就有多少种方法可以凑齐容量为5的背包。 +例如:dp[j],j 为5, -那么需要把 这些方法累加起来就可以了,dp[j] += dp[j - nums[i]] +* 已经有一个1(nums[i]) 的话,有 dp[4]种方法 凑成 dp[5]。 +* 已经有一个2(nums[i]) 的话,有 dp[3]种方法 凑成 dp[5]。 +* 已经有一个3(nums[i]) 的话,有 dp[2]中方法 凑成 dp[5] +* 已经有一个4(nums[i]) 的话,有 dp[1]中方法 凑成 dp[5] +* 已经有一个5 (nums[i])的话,有 dp[0]中方法 凑成 dp[5] + +那么凑整dp[5]有多少方法呢,也就是把 所有的 dp[j - nums[i]] 累加起来。 所以求组合类问题的公式,都是类似这种: diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index f039c198..f9dfa308 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -222,8 +222,8 @@ class Solution { } } ``` -Python: -```python3 +Python3: +```python class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: result = [-1]*len(nums1) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 277f46f5..a2984ecc 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -470,7 +470,7 @@ class Solution { > 递归法 -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): @@ -515,7 +515,7 @@ class Solution: > 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性 -```python3 +```python class Solution: def findMode(self, root: TreeNode) -> List[int]: stack = [] diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index c9532a22..36e183e1 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -124,7 +124,7 @@ class Solution { ``` Python: -```python3 +```python class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: dp = [-1] * len(nums) diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index be60ac13..e72c5f85 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -207,7 +207,7 @@ class Solution { Python: -```python3 +```python class Solution: def change(self, amount: int, coins: List[int]) -> int: dp = [0]*(amount + 1) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 1d11d4ee..1b07b803 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -196,7 +196,7 @@ class Solution { ## Python **递归** -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index d17c0b1c..15f6a040 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -264,7 +264,7 @@ class Solution { ## Python **递归** -```python3 +```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index 8397690e..1cd13065 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -152,7 +152,6 @@ class Solution { -Python: python3 diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 9a0bb1c1..b94e557d 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -194,7 +194,7 @@ class Solution { ``` Python: -```python3 +```python # 方法一,使用栈,推荐! class Solution: def removeDuplicates(self, s: str) -> str: @@ -207,7 +207,7 @@ class Solution: return "".join(res) # 字符串拼接 ``` -```python3 +```python # 方法二,使用双指针模拟栈,如果不让用栈可以作为备选方法。 class Solution: def removeDuplicates(self, s: str) -> str: diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index c481fd11..2fef68da 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -168,7 +168,7 @@ class Solution { ``` Python: -```python3 +```python # 前序遍历-递归-LC144_二叉树的前序遍历 class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: diff --git a/problems/周总结/20201003二叉树周末总结.md b/problems/周总结/20201003二叉树周末总结.md index a0b8c2dd..18bbf37f 100644 --- a/problems/周总结/20201003二叉树周末总结.md +++ b/problems/周总结/20201003二叉树周末总结.md @@ -34,8 +34,8 @@ public: // 此时就是:左右节点都不为空,且数值相同的情况 // 此时才做递归,做下一层的判断 - bool outside = compare(left->left, right->right); // 左子树:左、 右子树:左 (相对于求对称二叉树,只需改一下这里的顺序) - bool inside = compare(left->right, right->left); // 左子树:右、 右子树:右 + bool outside = compare(left->left, right->left); // 左子树:左、 右子树:左 (相对于求对称二叉树,只需改一下这里的顺序) + bool inside = compare(left->right, right->right); // 左子树:右、 右子树:右 bool isSame = outside && inside; // 左子树:中、 右子树:中 (逻辑处理) return isSame; diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index cea69c72..7abaf160 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -216,7 +216,7 @@ private static void testCompletePackAnotherWay(){ Python: -```python3 +```python # 先遍历物品,再遍历背包 def test_complete_pack1(): weight = [1, 3, 4] From 4b1542f8643f63ca9a09103642c680e05996e1a8 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 28 Feb 2022 21:02:53 +0800 Subject: [PATCH 170/257] =?UTF-8?q?1002=E6=9F=A5=E6=89=BE=E5=B8=B8?= =?UTF-8?q?=E7=94=A8=E5=AD=97=E7=AC=A6=E6=B7=BB=E5=8A=A0typescript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 7c5566d3..e3d4d774 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -253,6 +253,41 @@ var commonChars = function (words) { return res }; ``` +TypeScript +```ts + console.time("test") + let str: string = "" + //设置一个用字母组成的map字典 + let map = new Map() + //给所有map设置初始值为0 + let wordInitial: [string, number][] = words[0] + .split("") + .map((item) => [item, 0]) + //如果有重复字母,就把重复字母的数量加1 + for (let word of words[0]) { + map.set(word, map.has(word) ? map.get(word) + 1 : 1) + } + for (let i = 1; i < words.length; i++) { + const mapWord = new Map(wordInitial) + for (let j = 0; j < words[i].length; j++) { + if (!map.has(words[i][j])) continue + //mapWord中的字母的个数不能高于当前map的个数,多于则不能添加 + if (map.get(words[i][j]) > mapWord.get(words[i][j])) { + mapWord.set( + words[i][j], + mapWord.has(words[i][j]) ? mapWord!.get(words[i][j]) + 1 : 1 + ) + } + } + //每次重新初始化map + map = mapWord + } + for (let [key, value] of map) { + str += key.repeat(value) + } + console.timeEnd("test") + return str.split("") +``` GO ```golang func commonChars(words []string) []string { From fc5b272bd604dfe409a5c699d8253fde515b83ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BC=97=E8=B1=AA?= Date: Tue, 1 Mar 2022 08:56:51 +0800 Subject: [PATCH 171/257] =?UTF-8?q?fix:=200053.=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=92=20js=E4=BB=A3=E7=A0=81=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和(动态规划).md | 1 + 1 file changed, 1 insertion(+) diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index 37de9bbe..703e1dd6 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -174,6 +174,7 @@ const maxSubArray = nums => { // 数组长度,dp初始化 const len = nums.length; let dp = new Array(len).fill(0); + dp[0] = nums[0]; // 最大值初始化为dp[0] let max = dp[0]; for (let i = 1; i < len; i++) { From 66c3aab86a1c979ca14244c65ee2564be6e288d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8F=82=E7=8F=82?= Date: Tue, 1 Mar 2022 11:27:42 +0800 Subject: [PATCH 172/257] =?UTF-8?q?=E5=AF=B9=E4=BA=8E09=E8=BF=99=E6=A0=B7?= =?UTF-8?q?=E7=9A=84=E5=88=A4=E6=96=AD=E5=8F=AF=E4=BB=A5=E4=B8=8D=E5=81=9A?= =?UTF-8?q?=EF=BC=8C=E7=9B=B4=E6=8E=A5=E7=94=A8String.valueOf=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E5=B0=B1=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0738.单调递增的数字.md | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index e670bb31..c8ce8a2b 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -148,23 +148,19 @@ java版本1中创建了String数组,多次使用Integer.parseInt了方法, 版本2 class Solution { public int monotoneIncreasingDigits(int n) { - if (n==0)return 0; - char[] chars= Integer.toString(n).toCharArray(); - int start=Integer.MAX_VALUE;//start初始值设为最大值,这是为了防止当数字本身是单调递增时,没有一位数字需要改成9的情况 - for (int i=chars.length-1;i>0;i--){ - if (chars[i]= 0; i--) { + if (chars[i] > chars[i + 1]) { + chars[i]--; + start = i+1; } } - StringBuilder res=new StringBuilder(); - for (int i=0;i=start){ - res.append('9'); - }else res.append(chars[i]); + for (int i = start; i < s.length(); i++) { + chars[i] = '9'; } - return Integer.parseInt(res.toString()); + return Integer.parseInt(String.valueOf(chars)); } } ``` From 1ed3e9e8f4dff921e983e636f85f963a38839e05 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Tue, 1 Mar 2022 17:12:19 +0800 Subject: [PATCH 173/257] Update --- problems/二叉树总结篇.md | 2 +- problems/动态规划总结篇.md | 2 +- problems/回溯总结.md | 2 +- problems/贪心算法总结篇.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/problems/二叉树总结篇.md b/problems/二叉树总结篇.md index d1332e09..73faffa6 100644 --- a/problems/二叉树总结篇.md +++ b/problems/二叉树总结篇.md @@ -152,7 +152,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211030125421.png) -这个图是 [代码随想录知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842),所画,总结的非常好,分享给大家。 +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842),所画,总结的非常好,分享给大家。 **最后,二叉树系列就这么完美结束了,估计这应该是最长的系列了,感谢大家33天的坚持与陪伴,接下来我们又要开始新的系列了「回溯算法」!** diff --git a/problems/动态规划总结篇.md b/problems/动态规划总结篇.md index 699d4435..cc973b23 100644 --- a/problems/动态规划总结篇.md +++ b/problems/动态规划总结篇.md @@ -118,7 +118,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211121223754.png) -这个图是 [代码随想录知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842),所画,总结的非常好,分享给大家。 +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842),所画,总结的非常好,分享给大家。 这已经是全网对动规最深刻的讲解系列了。 diff --git a/problems/回溯总结.md b/problems/回溯总结.md index af171243..671e0a4e 100644 --- a/problems/回溯总结.md +++ b/problems/回溯总结.md @@ -432,7 +432,7 @@ N皇后问题分析: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211030124742.png) -这个图是 [代码随想录知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 成员:[莫非毛](https://wx.zsxq.com/dweb2/index/footprint/828844212542),所画,总结的非常好,分享给大家。 +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[莫非毛](https://wx.zsxq.com/dweb2/index/footprint/828844212542),所画,总结的非常好,分享给大家。 **回溯算法系列正式结束,新的系列终将开始,录友们准备开启新的征程!** diff --git a/problems/贪心算法总结篇.md b/problems/贪心算法总结篇.md index 6da43ea3..1db9b4dc 100644 --- a/problems/贪心算法总结篇.md +++ b/problems/贪心算法总结篇.md @@ -129,7 +129,7 @@ Carl个人认为:如果找出局部最优并可以推出全局最优,就是 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211110121605.png) -这个图是 [代码随想录知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842)所画,总结的非常好,分享给大家。 +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842)所画,总结的非常好,分享给大家。 很多没有接触过贪心的同学都会感觉贪心有啥可学的,但只要跟着「代码随想录」坚持下来之后,就会发现,贪心是一种很重要的算法思维而且并不简单,贪心往往妙的出其不意,触不及防! From e67bf9d4330aa3c7cf08f899aef2b11b3bba8cb8 Mon Sep 17 00:00:00 2001 From: Dawn-private <404232992@qq.com> Date: Tue, 1 Mar 2022 19:51:18 +0800 Subject: [PATCH 174/257] =?UTF-8?q?Update=200300.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E4=B8=8A=E5=8D=87=E5=AD=90=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改300.最长递增子序列动态数组的定义 --- problems/0300.最长上升子序列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index ed61a30e..dfdd5125 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -37,7 +37,7 @@ 1. dp[i]的定义 -**dp[i]表示i之前包括i的最长上升子序列的长度**。 +**dp[i]表示i之前包括i的以nums[i]结尾最长上升子序列的长度** 2. 状态转移方程 From 10c49296ff3b7d9d97fd1d061beb8db77e771be9 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 1 Mar 2022 21:28:59 +0800 Subject: [PATCH 175/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880236.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=A5=96=E5=85=88.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/0236.二叉树的最近公共祖先.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 6213aeaa..ca5fba77 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -325,6 +325,20 @@ var lowestCommonAncestor = function(root, p, q) { }; ``` +## TypeScript + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + if (root === null || root === p || root === q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (left !== null && right !== null) return root; + if (left !== null) return left; + if (right !== null) return right; + return null; +}; +``` + ----------------------- From d4e3da4c3db7729441397b7555b5a26b62fb8e2c Mon Sep 17 00:00:00 2001 From: Qiyu Liang <61932152+Guicai996@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:33:54 +0800 Subject: [PATCH 176/257] =?UTF-8?q?Update=200139.=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8B=86=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除原Line 102,修改memory数组为bool型 因为根据执行顺序,Line 101的if判断句,只有在前一个判断返回true的时候才会递归,因此若执行到memory[startIndex] = 1时,程序已经完成了遍历,memory[startIndex] = 1的情况完全没用的上。而memory用上的情况为false重复,即程序已经判断过startIndex开头无法分割。 --- problems/0139.单词拆分.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 1653a81a..e04cb173 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -89,27 +89,26 @@ class Solution { private: bool backtracking (const string& s, const unordered_set& wordSet, - vector& memory, + vector& memory, int startIndex) { if (startIndex >= s.size()) { return true; } // 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果 - if (memory[startIndex] != -1) return memory[startIndex]; + if (!memory[startIndex]) return memory[startIndex]; for (int i = startIndex; i < s.size(); i++) { string word = s.substr(startIndex, i - startIndex + 1); if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) { - memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的 return true; } } - memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的 + memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的 return false; } public: bool wordBreak(string s, vector& wordDict) { unordered_set wordSet(wordDict.begin(), wordDict.end()); - vector memory(s.size(), -1); // -1 表示初始化状态 + vector memory(s.size(), 1); // -1 表示初始化状态 return backtracking(s, wordSet, memory, 0); } }; From 58ffbd146ba7250eba350b688f2bed095495e012 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:40:17 +0800 Subject: [PATCH 177/257] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200116.=E5=A1=AB?= =?UTF-8?q?=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87?= =?UTF-8?q?=E9=92=88.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0116.填充每个节点的下一个右侧节点指针.md | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index bc3a8c6b..2c443de5 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -211,9 +211,52 @@ class Solution: return root ``` ## Go - ```go - +// 迭代法 +func connect(root *Node) *Node { + if root == nil { + return root + } + stack := make([]*Node, 0) + stack = append(stack, root) + for len(stack) > 0 { + n := len(stack) // 记录当前层节点个数 + for i := 0; i < n; i++ { + node := stack[0] // 依次弹出节点 + stack = stack[1:] + if i == n - 1 { // 如果是这层最右的节点,next指向nil + node.Next = nil + } else { + node.Next = stack[0] // 如果不是最右的节点,next指向右边的节点 + } + if node.Left != nil { // 如果存在左子节点,放入栈中 + stack = append(stack, node.Left) + } + if node.Right != nil { // 如果存在右子节点,放入栈中 + stack = append(stack, node.Right) + } + } + } + return root +} +``` +```go +// 常量级额外空间,使用next +func connect(root *Node) *Node { + if root == nil { + return root + } + for cur := root; cur.Left != nil; cur = cur.Left { // 遍历每层最左边的节点 + for node := cur; node != nil; node = node.Next { // 当前层从左到右遍历 + node.Left.Next = node.Right // 左子节点next指向右子节点 + if node.Next != nil { //如果node next有值,右子节点指向next节点的左子节点 + node.Right.Next = node.Next.Left + } + + } + } + return root +} ``` ## JavaScript From 246bbe921c5a09cc0f440bb97a75cf92067fd950 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 2 Mar 2022 14:20:44 +0800 Subject: [PATCH 178/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880235.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88.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/0235.二叉搜索树的最近公共祖先.md | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index b9d0a0bf..f7f1427a 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -350,6 +350,39 @@ var lowestCommonAncestor = function(root, p, q) { }; ``` +## TypeScript + +> 递归法: + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + if (root.val > p.val && root.val > q.val) + return lowestCommonAncestor(root.left, p, q); + if (root.val < p.val && root.val < q.val) + return lowestCommonAncestor(root.right, p, q); + return root; +}; +``` + +> 迭代法: + +```typescript +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + while (root !== null) { + if (root.val > p.val && root.val > q.val) { + root = root.left; + } else if (root.val < p.val && root.val < q.val) { + root = root.right; + } else { + return root; + }; + }; + return null; +}; +``` + + + -----------------------
From 32c54b4a5604aecab1681a84a8a58ed29b9a1151 Mon Sep 17 00:00:00 2001 From: Wayne <3522373084@qq.com> Date: Wed, 2 Mar 2022 16:03:14 +0800 Subject: [PATCH 179/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20968=20=E7=9B=91?= =?UTF-8?q?=E6=8E=A7=E4=BA=8C=E5=8F=89=E6=A0=91=20Java=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81,=E5=A2=9E=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0968.监控二叉树.md | 50 ++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 433060a5..35c3ccdc 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -316,28 +316,44 @@ public: ### Java ```java class Solution { - private int count = 0; + int res=0; public int minCameraCover(TreeNode root) { - if (trval(root) == 0) count++; - return count; + // 对根节点的状态做检验,防止根节点是无覆盖状态 . + if(minCame(root)==0){ + res++; + } + return res; } - - private int trval(TreeNode root) { - if (root == null) return -1; - - int left = trval(root.left); - int right = trval(root.right); - - if (left == 0 || right == 0) { - count++; + /** + 节点的状态值: + 0 表示无覆盖 + 1 表示 有摄像头 + 2 表示有覆盖 + 后序遍历,根据左右节点的情况,来判读 自己的状态 + */ + public int minCame(TreeNode root){ + if(root==null){ + // 空节点默认为 有覆盖状态,避免在叶子节点上放摄像头 return 2; } - - if (left == 2 || right == 2) { + int left=minCame(root.left); + int right=minCame(root.right); + + // 如果左右节点都覆盖了的话, 那么本节点的状态就应该是无覆盖,没有摄像头 + if(left==2&&right==2){ + //(2,2) + return 0; + }else if(left==0||right==0){ + // 左右节点都是无覆盖状态,那 根节点此时应该放一个摄像头 + // (0,0) (0,1) (0,2) (1,0) (2,0) + // 状态值为 1 摄像头数 ++; + res++; return 1; + }else{ + // 左右节点的 状态为 (1,1) (1,2) (2,1) 也就是左右节点至少存在 1个摄像头, + // 那么本节点就是处于被覆盖状态 + return 2; } - - return 0; } } ``` @@ -391,7 +407,7 @@ class Solution: result += 1 return result -``` +``` ### Go ```go From f4b55a1e4abb3e0ac0ae49c8126ee6a827c19447 Mon Sep 17 00:00:00 2001 From: ashing Date: Wed, 2 Mar 2022 21:10:26 +0800 Subject: [PATCH 180/257] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=A4=9A=E9=87=8D?= =?UTF-8?q?=E8=83=8C=E5=8C=85.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充 go 多重背包理论 --- problems/背包问题理论基础多重背包.md | 87 ++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md index 80b9f8a1..d05c3445 100644 --- a/problems/背包问题理论基础多重背包.md +++ b/problems/背包问题理论基础多重背包.md @@ -245,7 +245,94 @@ if __name__ == '__main__': Go: +```go +package theory +import "log" + +// 多重背包可以化解为 01 背包 +func multiplePack(weight, value, nums []int, bagWeight int) int { + + for i := 0; i < len(nums); i++ { + for nums[i] > 1 { + weight = append(weight, weight[i]) + value = append(value, value[i]) + nums[i]-- + } + } + log.Println(weight) + log.Println(value) + + res := make([]int, bagWeight+1) + for i := 0; i < len(weight); i++ { + for j := bagWeight; j >= weight[i]; j-- { + res[j] = getMax(res[j], res[j-weight[i]]+value[i]) + } + log.Println(res) + } + + return res[bagWeight] +} +``` + +> 单元测试 + +```go +package theory + +import "testing" + +func Test_multiplePack(t *testing.T) { + type args struct { + weight []int + value []int + nums []int + bagWeight int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "one", + args: args{ + weight: []int{1, 3, 4}, + value: []int{15, 20, 30}, + nums: []int{2, 3, 2}, + bagWeight: 10, + }, + want: 90, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := multiplePack(tt.args.weight, tt.args.value, tt.args.nums, tt.args.bagWeight); got != tt.want { + t.Errorf("multiplePack() = %v, want %v", got, tt.want) + } + }) + } +} +``` + +> 输出 + +``` +=== RUN Test_multiplePack +=== RUN Test_multiplePack/one +2022/03/02 21:09:05 [1 3 4 1 3 3 4] +2022/03/02 21:09:05 [15 20 30 15 20 20 30] +2022/03/02 21:09:05 [0 15 15 15 15 15 15 15 15 15 15] +2022/03/02 21:09:05 [0 15 15 20 35 35 35 35 35 35 35] +2022/03/02 21:09:05 [0 15 15 20 35 45 45 50 65 65 65] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 65 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 80] +2022/03/02 21:09:05 [0 15 30 30 35 50 60 60 70 80 90] +--- PASS: Test_multiplePack (0.00s) + --- PASS: Test_multiplePack/one (0.00s) +PASS +``` ----------------------- From f2c75c27af3bd0ed9881faaa820529730068e353 Mon Sep 17 00:00:00 2001 From: kinsozheng Date: Wed, 2 Mar 2022 22:25:00 +0800 Subject: [PATCH 181/257] =?UTF-8?q?=E4=BF=AE=E6=94=B90018=E5=9B=9B?= =?UTF-8?q?=E6=95=B0=E4=B9=8B=E5=92=8C=20Python=E7=89=88=E6=9C=AC=20?= =?UTF-8?q?=E5=93=88=E5=B8=8C=E8=A1=A8=E6=B3=95=E8=A7=A3=E6=B3=95=20?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E7=94=A8set()=E5=AD=98=E5=82=A8=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E7=BB=93=E6=9E=9C=E4=BD=86=E6=98=AF=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E6=8A=A5=E9=94=99=E7=9A=84=E9=97=AE=E9=A2=98=20=E5=90=8C?= =?UTF-8?q?=E6=97=B6=E5=8A=A0=E5=85=A5=E4=BB=A5list()=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E7=9A=84=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0018.四数之和.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index bad258c1..348f2f73 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -212,6 +212,7 @@ class Solution(object): # good thing about using python is you can use set to drop duplicates. ans = set() + # ans = [] # save results by list() for i in range(len(nums)): for j in range(i + 1, len(nums)): for k in range(j + 1, len(nums)): @@ -220,10 +221,16 @@ class Solution(object): # make sure no duplicates. count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val) if hashmap[val] > count: - ans.add(tuple(sorted([nums[i], nums[j], nums[k], val]))) - else: - continue - return ans + ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val])) + ans.add(ans_tmp) + # Avoiding duplication in list manner but it cause time complexity increases + # if ans_tmp not in ans: + # ans.append(ans_tmp) + else: + continue + return list(ans) + # if used list() to save results, just + # return ans ``` From 70ea2c76eab540df65f34f79f5ba425ba50c54c7 Mon Sep 17 00:00:00 2001 From: wangming Date: Thu, 3 Mar 2022 16:29:41 +0800 Subject: [PATCH 182/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A00309.=E6=9C=80?= =?UTF-8?q?=E4=BD=B3=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E6=97=B6=E6=9C=BA?= =?UTF-8?q?=E5=90=AB=E5=86=B7=E5=86=BB=E6=9C=9Fjs=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0309.最佳买卖股票时机含冷冻期.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 2dc1e874..bb8909cd 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -284,6 +284,24 @@ const maxProfit = (prices) => { }; ``` +```javascript +// 一维数组空间优化 +const maxProfit = (prices) => { + const n = prices.length + const dp = new Array(4).fill(0) + dp[0] = -prices[0] + for (let i = 1; i < n; i ++) { + const temp = dp[0] // 缓存上一次的状态 + const temp1 = dp[2] + dp[0] = Math.max(dp[0], Math.max(dp[3] - prices[i], dp[1] - prices[i])) // 持有状态 + dp[1] = Math.max(dp[1], dp[3]) // 今天不操作且不持有股票 + dp[2] = temp + prices[i] // 今天卖出股票 + dp[3] = temp1 // 冷冻期 + } + return Math.max(...dp) +}; +``` + -----------------------
From cc302a9e8d43440605c4a61bde398784800c2b5e Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Fri, 4 Mar 2022 10:52:42 +1100 Subject: [PATCH 183/257] =?UTF-8?q?Update=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The variable cur could be null, should add the union to the type of cur. --- problems/0203.移除链表元素.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 4e7bdd34..c0e0be3e 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -324,7 +324,7 @@ function removeElements(head: ListNode | null, val: number): ListNode | null { head = head.next; } if (head === null) return head; - let pre: ListNode = head, cur: ListNode = head.next; + let pre: ListNode = head, cur: ListNode | null = head.next; // 删除非头部节点 while (cur) { if (cur.val === val) { From 09c1bd818abf8da2c1c426a06e46f2063b0089b0 Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Fri, 4 Mar 2022 11:12:33 +1100 Subject: [PATCH 184/257] =?UTF-8?q?Update=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Creating a dummy head variable makes the logic clear. --- problems/0203.移除链表元素.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 4e7bdd34..d2ba1ae8 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -342,14 +342,14 @@ function removeElements(head: ListNode | null, val: number): ListNode | null { ```typescript function removeElements(head: ListNode | null, val: number): ListNode | null { - head = new ListNode(0, head); - let pre: ListNode = head, cur: ListNode = head.next; + let dummyHead = new ListNode(0, head); + let pre: ListNode = dummyHead, cur: ListNode | null = dummyHead.next; // 删除非头部节点 while (cur) { if (cur.val === val) { pre.next = cur.next; } else { - pre = pre.next; + pre = cur; } cur = cur.next; } From e83846db0413bdcb6be0509eb987d3d2d685de50 Mon Sep 17 00:00:00 2001 From: ClorisMoQi <748709762@qq.com> Date: Thu, 3 Mar 2022 22:40:31 -0800 Subject: [PATCH 185/257] add explanation for go slice --- problems/O(n)的算法居然超时了,此时的n究竟是多大?.md | 6 ++++++ problems/根据身高重建队列(vector原理讲解).md | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md index 4de56597..66db2b83 100644 --- a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md @@ -226,7 +226,13 @@ Python: Go: +Go中slice的`append`操作和C++中vector的扩容机制基本相同。 +说是基本呢,其实是因为大家平时刷题和工作中遇到的数据不会特别大。 + +具体来说,当当前slice的长度小于**1024**时,执行`append`操作,新slice的capacity会变成当前的2倍;而当slice长度大于等于**1024**时,slice的扩容变成了每次增加当前slice长度的**1/4**。 + +在Go Slice的底层实现中,如果capacity不够时,会做一个reslice的操作,底层数组也会重新被复制到另一块内存区域中,所以`append`一个元素,不一定是O(1), 也可能是O(n)哦。 ----------------------- diff --git a/problems/根据身高重建队列(vector原理讲解).md b/problems/根据身高重建队列(vector原理讲解).md index 11a72e2d..28317e6c 100644 --- a/problems/根据身高重建队列(vector原理讲解).md +++ b/problems/根据身高重建队列(vector原理讲解).md @@ -171,6 +171,14 @@ Python: Go: +Go中slice的`append`操作和C++中vector的扩容机制基本相同。 + +说是基本呢,其实是因为大家平时刷题和工作中遇到的数据不会特别大。 + +具体来说,当当前slice的长度小于**1024**时,执行`append`操作,新slice的capacity会变成当前的2倍;而当slice长度大于等于**1024**时,slice的扩容变成了每次增加当前slice长度的**1/4**。 + +在Go Slice的底层实现中,如果capacity不够时,会做一个reslice的操作,底层数组也会重新被复制到另一块内存区域中,所以`append`一个元素,不一定是O(1), 也可能是O(n)哦。 + From 3ec2f7ff537407c036edabfab126d9190e0d299b Mon Sep 17 00:00:00 2001 From: ClorisMoQi <748709762@qq.com> Date: Thu, 3 Mar 2022 22:42:07 -0800 Subject: [PATCH 186/257] add explanation for go slice --- problems/O(n)的算法居然超时了,此时的n究竟是多大?.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md index 66db2b83..4de56597 100644 --- a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md @@ -226,13 +226,7 @@ Python: Go: -Go中slice的`append`操作和C++中vector的扩容机制基本相同。 -说是基本呢,其实是因为大家平时刷题和工作中遇到的数据不会特别大。 - -具体来说,当当前slice的长度小于**1024**时,执行`append`操作,新slice的capacity会变成当前的2倍;而当slice长度大于等于**1024**时,slice的扩容变成了每次增加当前slice长度的**1/4**。 - -在Go Slice的底层实现中,如果capacity不够时,会做一个reslice的操作,底层数组也会重新被复制到另一块内存区域中,所以`append`一个元素,不一定是O(1), 也可能是O(n)哦。 ----------------------- From 8cf3fabb60a29966bb725b223ada9d92d7aa5bb1 Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Sat, 5 Mar 2022 11:41:05 +1100 Subject: [PATCH 187/257] =?UTF-8?q?Update=200024.=E4=B8=A4=E4=B8=A4?= =?UTF-8?q?=E4=BA=A4=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TypeScript version code that better matches your c++ code example. --- problems/0024.两两交换链表中的节点.md | 40 ++++++++++----------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index bf1fd5e1..ce75e0d7 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -254,32 +254,20 @@ TypeScript: ```typescript function swapPairs(head: ListNode | null): ListNode | null { - /** - * 初始状态: - * curNode -> node1 -> node2 -> tmepNode - * 转换过程: - * curNode -> node2 - * curNode -> node2 -> node1 - * curNode -> node2 -> node1 -> tempNode - * curNode = node1 - */ - let retNode: ListNode | null = new ListNode(0, head), - curNode: ListNode | null = retNode, - node1: ListNode | null = null, - node2: ListNode | null = null, - tempNode: ListNode | null = null; - - while (curNode && curNode.next && curNode.next.next) { - node1 = curNode.next; - node2 = curNode.next.next; - tempNode = node2.next; - curNode.next = node2; - node2.next = node1; - node1.next = tempNode; - curNode = node1; - } - return retNode.next; -}; + const dummyHead: ListNode = new ListNode(0, head); + let cur: ListNode = dummyHead; + while(cur.next !== null && cur.next.next !== null) { + const tem: ListNode = cur.next; + const tem1: ListNode = cur.next.next.next; + + cur.next = cur.next.next; // step 1 + cur.next.next = tem; // step 2 + cur.next.next.next = tem1; // step 3 + + cur = cur.next.next; + } + return dummyHead.next; +} ``` Kotlin: From d701e5e2aa80d44a24fbc54e241d6589e34d4b12 Mon Sep 17 00:00:00 2001 From: Wayne <3522373084@qq.com> Date: Sat, 5 Mar 2022 10:59:03 +0800 Subject: [PATCH 188/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9739=20=E6=AF=8F?= =?UTF-8?q?=E6=97=A5=E6=B8=A9=E5=BA=A6=E7=9A=84=20Java=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81,=E5=B9=B6=E5=A2=9E=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0739.每日温度.md | 76 ++++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 25 deletions(-) diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index d7489028..bdc75b96 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -177,34 +177,60 @@ public: Java: ```java -/** - * 单调栈,栈内顺序要么从大到小 要么从小到大,本题从大到小 - *

- * 入站元素要和当前栈内栈首元素进行比较 - * 若大于栈首则 则与元素下标做差 - * 若大于等于则放入 - * - * @param temperatures - * @return - */ - public static int[] dailyTemperatures(int[] temperatures) { - Stack stack = new Stack<>(); - int[] res = new int[temperatures.length]; - for (int i = 0; i < temperatures.length; i++) { - /** - * 取出下标进行元素值的比较 - */ - while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { - int preIndex = stack.pop(); - res[preIndex] = i - preIndex; + +class Solution { + // 版本 1 + public int[] dailyTemperatures(int[] temperatures) { + + int lens=temperatures.length; + int []res=new int[lens]; + + /** + 如果当前遍历的元素 大于栈顶元素,表示 栈顶元素的 右边的最大的元素就是 当前遍历的元素, + 所以弹出 栈顶元素,并记录 + 如果栈不空的话,还要考虑新的栈顶与当前元素的大小关系 + 否则的话,可以直接入栈。 + 注意,单调栈里 加入的元素是 下标。 + */ + Stackstack=new Stack<>(); + stack.push(0); + for(int i=1;itemperatures[stack.peek()]){ + res[stack.peek()]=i-stack.peek(); + stack.pop(); + } + stack.push(i); } - /** - * 注意 放入的是元素位置 - */ - stack.push(i); } - return res; + + return res; } + + //--------这 是一条分界线 + // 版本 2 + class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int lens=temperatures.length; + int []res=new int[lens]; + Stackstack=new Stack<>(); + for(int i=0;itemperatures[stack.peek()]){ + res[stack.peek()]=i-stack.peek(); + stack.pop(); + } + stack.push(i); + } + + return res; + } +} + +} ``` Python: ``` Python3 From ecde43b2fc292edbfaa1fec6b16d6941e879507f Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Sat, 5 Mar 2022 17:12:34 +0800 Subject: [PATCH 189/257] update --- problems/0392.判断子序列.md | 2 +- problems/背包总结篇.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/problems/0392.判断子序列.md b/problems/0392.判断子序列.md index d64e1fd0..671576f7 100644 --- a/problems/0392.判断子序列.md +++ b/problems/0392.判断子序列.md @@ -77,7 +77,7 @@ if (s[i - 1] != t[j - 1]),此时相当于t要删除元素,t如果把当前 如果要是定义的dp[i][j]是以下标i为结尾的字符串s和以下标j为结尾的字符串t,初始化就比较麻烦了。 -这里dp[i][0]和dp[0][j]是没有含义的,仅仅是为了给递推公式做前期铺垫,所以初始化为0。 +dp[i][0] 表示以下标i-1为结尾的字符串,与空字符串的相同子序列长度,所以为0. dp[0][j]同理。 **其实这里只初始化dp[i][0]就够了,但一起初始化也方便,所以就一起操作了**,代码如下: diff --git a/problems/背包总结篇.md b/problems/背包总结篇.md index f80bcf29..a7852de3 100644 --- a/problems/背包总结篇.md +++ b/problems/背包总结篇.md @@ -82,6 +82,7 @@ ## 总结 + **这篇背包问题总结篇是对背包问题的高度概括,讲最关键的两部:递推公式和遍历顺序,结合力扣上的题目全都抽象出来了**。 **而且每一个点,我都给出了对应的力扣题目**。 @@ -90,7 +91,11 @@ 如果把我本篇总结出来的内容都掌握的话,可以说对背包问题理解的就很深刻了,用来对付面试中的背包问题绰绰有余! +背包问题总结: +![](https://code-thinking-1253855093.file.myqcloud.com/pics/背包问题1.jpeg) + +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[海螺人](https://wx.zsxq.com/dweb2/index/footprint/844412858822412),所画结的非常好,分享给大家。 From f6360c701f5e1d251ad69e15c94c05273ff4235c Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Sun, 6 Mar 2022 11:44:39 +0800 Subject: [PATCH 190/257] Update --- README.md | 5 ++--- problems/前序/ACM模式如何构建二叉树.md | 16 +--------------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index c1761f7b..0bf7fcdf 100644 --- a/README.md +++ b/README.md @@ -89,8 +89,7 @@ ## 前序 -* [「代码随想录」后序安排](https://mp.weixin.qq.com/s/4eeGJREy6E-v6D7cR_5A4g) -* [「代码随想录」学习社区](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +* [「代码随想录」学习社区](https://programmercarl.com/other/kstar.html) * 编程语言 @@ -124,7 +123,7 @@ * 算法性能分析 * [关于时间复杂度,你不知道的都在这里!](./problems/前序/关于时间复杂度,你不知道的都在这里!.md) - * [$O(n)$的算法居然超时了,此时的n究竟是多大?](./problems/前序/On的算法居然超时了,此时的n究竟是多大?.md) + * [O(n)的算法居然超时了,此时的n究竟是多大?](./problems/前序/On的算法居然超时了,此时的n究竟是多大?.md) * [通过一道面试题目,讲一讲递归算法的时间复杂度!](./problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md) * [本周小结!(算法性能分析系列一)](./problems/周总结/20201210复杂度分析周末总结.md) * [关于空间复杂度,可能有几个疑问?](./problems/前序/关于空间复杂度,可能有几个疑问?.md) diff --git a/problems/前序/ACM模式如何构建二叉树.md b/problems/前序/ACM模式如何构建二叉树.md index fc7a1823..28c4b6f7 100644 --- a/problems/前序/ACM模式如何构建二叉树.md +++ b/problems/前序/ACM模式如何构建二叉树.md @@ -45,21 +45,7 @@ ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210914223147.png) -那么此时大家是不是应该知道了,数组如何转化成 二叉树了。**如果父节点的数组下标是i,那么它的左孩子下标就是i * 2 + 1,右孩子下标就是 i * 2 + 2**。计算过程为: - -如果父节点在第$k$层,第$m,m \in [0,2^k]$个节点,则其左孩子所在的位置必然为$k+1$层,第$2*(m-1)+1$个节点。 - -- 计算父节点在数组中的索引: - $$ - index_{father}=(\sum_{i=0}^{i=k-1}2^i)+m-1=2^k-1+m-1 - $$ - -- 计算左子节点在数组的索引: - $$ - index_{left}=(\sum_{i=0}^{i=k}2^i)+2*m-1-1=2^{k+1}+2m-3 - $$ - -- 故左孩子的下表为$index_{left}=index_{father}\times2+1$,同理可得到右子孩子的索引关系。也可以直接在左子孩子的基础上`+1`。 +那么此时大家是不是应该知道了,数组如何转化成 二叉树了。**如果父节点的数组下标是i,那么它的左孩子下标就是i * 2 + 1,右孩子下标就是 i * 2 + 2**。 那么这里又有同学疑惑了,这些我都懂了,但我还是不知道 应该 怎么构造。 From d285d3d6b812a607bc31501a73a50a63222398d3 Mon Sep 17 00:00:00 2001 From: Younglesszzz <61218410+Younglesszzz@users.noreply.github.com> Date: Sun, 6 Mar 2022 20:54:25 +0800 Subject: [PATCH 191/257] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E4=BA=86=E5=9B=9E?= =?UTF-8?q?=E6=BA=AF+=E8=AE=B0=E5=BF=86=E7=9A=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 经过提交验证,其实memo[startIndex] = 1的这个逻辑根本没有用到,因为如果返回true,那么会如同dfs一样直接返回,不会再进行下一步的backtracking搜索,本题的记忆法核心是令memo[startIndex]置为-1,来避免从相同的startIndex开始拆分,导致程序进行大量重复运算,这应该也是本题剪枝方法的核心。 --- problems/0139.单词拆分.md | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 1653a81a..a54b849a 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -251,30 +251,34 @@ class Solution { // 回溯法+记忆化 class Solution { + private Set set; + private int[] memo; public boolean wordBreak(String s, List wordDict) { - Set wordDictSet = new HashSet(wordDict); - int[] memory = new int[s.length()]; - return backTrack(s, wordDictSet, 0, memory); + memo = new int[s.length()]; + set = new HashSet<>(wordDict); + return backtracking(s, 0); } - - public boolean backTrack(String s, Set wordDictSet, int startIndex, int[] memory) { - // 结束条件 - if (startIndex >= s.length()) { + + public boolean backtracking(String s, int startIndex) { + // System.out.println(startIndex); + if (startIndex == s.length()) { return true; } - if (memory[startIndex] != 0) { - // 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能 - return memory[startIndex] == 1 ? true : false; + if (memo[startIndex] == -1) { + return false; } - for (int i = startIndex; i < s.length(); ++i) { - // 处理 递归 回溯 循环不变量:[startIndex, i + 1) - String word = s.substring(startIndex, i + 1); - if (wordDictSet.contains(word) && backTrack(s, wordDictSet, i + 1, memory)) { - memory[startIndex] = 1; - return true; + + for (int i = startIndex; i < s.length(); i++) { + String sub = s.substring(startIndex, i + 1); + // 拆分出来的单词无法匹配 + if (!set.contains(sub)) { + continue; } + boolean res = backtracking(s, i + 1); + if (res) return true; } - memory[startIndex] = -1; + // 这里是关键,找遍了startIndex~s.length()也没能完全匹配,标记从startIndex开始不能找到 + memo[startIndex] = -1; return false; } } From 6e3f394893c39edae8864fffc71eee986e81361f Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Mon, 7 Mar 2022 00:33:30 +0800 Subject: [PATCH 192/257] Add level order traversal --- problems/0101.对称二叉树.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index e4e232c8..0007b4d4 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -437,6 +437,41 @@ class Solution: return True ``` +层序遍历 + +```python +class Solution: + def isSymmetric(self, root: TreeNode) -> bool: + if not root: return True + que, cnt = [[root.left, root.right]], 1 + while que: + nodes, tmp, sign = que.pop(), [], False + for node in nodes: + if not node: + tmp.append(None) + tmp.append(None) + else: + if node.left: + tmp.append(node.left) + sign = True + else: + tmp.append(None) + if node.right: + tmp.append(node.right) + sign = True + else: + tmp.append(None) + p1, p2 = 0, len(nodes) - 1 + while p1 < p2: + if (not nodes[p1] and nodes[p2]) or (nodes[p1] and not nodes[p2]): return False + elif nodes[p1] and nodes[p2] and nodes[p1].val != nodes[p2].val: return False + p1 += 1 + p2 -= 1 + if sign: que.append(tmp) + cnt += 1 + return True +``` + ## Go ```go From 94bf8916eef21cd40b2eb7b04cf67b2bf32ed6f6 Mon Sep 17 00:00:00 2001 From: Aaron-Lin-74 <84072071+Aaron-Lin-74@users.noreply.github.com> Date: Mon, 7 Mar 2022 10:15:06 +1100 Subject: [PATCH 193/257] =?UTF-8?q?Update=201002.=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add TypeScript solution. --- problems/1002.查找常用字符.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 7c5566d3..efad1e6a 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -253,6 +253,41 @@ var commonChars = function (words) { return res }; ``` + +TypeScript +```ts +function commonChars(words: string[]): string[] { + let result: string[] = []; + if (words.length === 0) return result; + const size: number = 26; + const hash: number[] = new Array(size).fill(0); + const otherHash: number[] = new Array(size).fill(0); + let pivot: number = 'a'.charCodeAt(0); + // First word + for (let character of words[0]) { + hash[character.charCodeAt(0) - pivot]++; + } + // Other words + for (let i = 1; i < words.length; i++) { + for (let character of words[i]) { + otherHash[character.charCodeAt(0) - pivot]++; + } + // Update the first hash with min + for (let j = 0; j < size; j++) { + hash[j] = Math.min(hash[j], otherHash[j]); + } + // Reset otherHash + otherHash.fill(0); + } + // Construct the result + hash.forEach((element, index) => { + while (element-- > 0) { + result.push(String.fromCharCode(index + pivot)); + } + }); + return result; +} +``` GO ```golang func commonChars(words []string) []string { From b79f3e0fb75ceefdc7b7db1b9f60fd53e3c3fee0 Mon Sep 17 00:00:00 2001 From: wutianjue Date: Mon, 7 Mar 2022 14:38:03 +0800 Subject: [PATCH 194/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=AF=8F=E4=B8=AA?= =?UTF-8?q?=E6=A0=91=E8=A1=8C=E4=B8=AD=E6=89=BE=E6=9C=80=E5=A4=A7=E5=80=BC?= =?UTF-8?q?Java=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 34 +++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 74485848..42380b15 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1300,23 +1300,23 @@ java代码: ```java class Solution { public List largestValues(TreeNode root) { - List retVal = new ArrayList(); - Queue tmpQueue = new LinkedList(); - if (root != null) tmpQueue.add(root); - - while (tmpQueue.size() != 0){ - int size = tmpQueue.size(); - List lvlVals = new ArrayList(); - for (int index = 0; index < size; index++){ - TreeNode node = tmpQueue.poll(); - lvlVals.add(node.val); - if (node.left != null) tmpQueue.add(node.left); - if (node.right != null) tmpQueue.add(node.right); - } - retVal.add(Collections.max(lvlVals)); - } - - return retVal; + if(root == null){ + return Collections.emptyList(); + } + List result = new ArrayList(); + Queue queue = new LinkedList(); + queue.offer(root); + while(!queue.isEmpty()){ + int max = Integer.MIN_VALUE; + for(int i = queue.size(); i > 0; i--){ + TreeNode node = queue.poll(); + max = Math.max(max, node.val); + if(node.left != null) queue.offer(node.left); + if(node.right != null) queue.offer(node.right); + } + result.add(max); + } + return result; } } ``` From a33f315175ff76061cbafc2b53a309f75db9890f Mon Sep 17 00:00:00 2001 From: tlylt Date: Mon, 7 Mar 2022 15:26:18 +0800 Subject: [PATCH 195/257] Fix spelling error --- problems/0416.分割等和子集.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 9da1f8d5..a4e780ab 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -253,14 +253,14 @@ Python: ```python class Solution: def canPartition(self, nums: List[int]) -> bool: - taraget = sum(nums) - if taraget % 2 == 1: return False - taraget //= 2 + target = sum(nums) + if target % 2 == 1: return False + target //= 2 dp = [0] * 10001 for i in range(len(nums)): - for j in range(taraget, nums[i] - 1, -1): + for j in range(target, nums[i] - 1, -1): dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]) - return taraget == dp[taraget] + return target == dp[target] ``` Go: ```go From 5a848b76c184a447bdc96d8afe40071bbf7f9cd0 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Wed, 9 Mar 2022 11:22:51 +0800 Subject: [PATCH 196/257] Update --- problems/0127.单词接龙.md | 1 - problems/二叉树理论基础.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index fb403a5b..407596c0 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -9,7 +9,6 @@ [力扣题目链接](https://leetcode-cn.com/problems/word-ladder/) - 字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列: * 序列中第一个单词是 beginWord 。 * 序列中最后一个单词是 endWord 。 diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 62e3b19a..9c151e32 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -33,7 +33,7 @@ 什么是完全二叉树? -完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^h -1  个节点。 +完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1)  个节点。 **大家要自己看完全二叉树的定义,很多同学对完全二叉树其实不是真正的懂了。** From ea31f6e70c277b527f90fce96dacb59a660f8956 Mon Sep 17 00:00:00 2001 From: berserk-112 <40333359+berserk-112@users.noreply.github.com> Date: Wed, 9 Mar 2022 12:05:30 +0800 Subject: [PATCH 197/257] =?UTF-8?q?Update=200309.=E6=9C=80=E4=BD=B3?= =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E6=97=B6=E6=9C=BA=E5=90=AB?= =?UTF-8?q?=E5=86=B7=E5=86=BB=E6=9C=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加了java版本的另一种解题思路,无需考虑多种状态,还是只考虑持有与未持有两种状态 --- problems/0309.最佳买卖股票时机含冷冻期.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 2dc1e874..53caa46e 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -205,6 +205,29 @@ class Solution { } } ``` +```java +//另一种解题思路 +class Solution { + public int maxProfit(int[] prices) { + int[][] dp = new int[prices.length + 1][2]; + dp[1][0] = -prices[0]; + + for (int i = 2; i <= prices.length; i++) { + /* + dp[i][0] 第i天未持有股票收益; + dp[i][1] 第i天持有股票收益; + 情况一:第i天是冷静期,不能以dp[i-1][1]购买股票,所以以dp[i - 2][1]买股票,没问题 + 情况二:第i天不是冷静期,理论上应该以dp[i-1][1]购买股票,但是第i天不是冷静期说明,第i-1天没有卖出股票, + 则dp[i-1][1]=dp[i-2][1],所以可以用dp[i-2][1]买股票,没问题 + */ + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 2][1] - prices[i - 1]); + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i - 1]); + } + + return dp[prices.length][1]; + } +} +``` Python: From 6c3c8c7bff1bf90f4a79259c0b7abd2434fd9d72 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 11 Mar 2022 11:35:14 +0800 Subject: [PATCH 198/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880701.?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E6=8F=92=E5=85=A5=E6=93=8D=E4=BD=9C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0701.二叉搜索树中的插入操作.md | 72 +++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 3 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 5e9fbdfe..df6a3954 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -280,7 +280,7 @@ class Solution: # 返回更新后的以当前root为根节点的新树 return roo -``` +``` **递归法** - 无返回值 ```python @@ -308,7 +308,7 @@ class Solution: return __traverse(root, val) return root -``` +``` **递归法** - 无返回值 - another easier way ```python @@ -378,7 +378,7 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { } return root } -``` +``` 迭代法 @@ -520,5 +520,71 @@ var insertIntoBST = function (root, val) { }; ``` +## TypeScript + +> 递归-有返回值 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + if (root.val > val) { + root.left = insertIntoBST(root.left, val); + } else { + root.right = insertIntoBST(root.right, val); + } + return root; +}; +``` + +> 递归-无返回值 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + function recur(root: TreeNode | null, val: number) { + if (root === null) { + if (parentNode.val > val) { + parentNode.left = new TreeNode(val); + } else { + parentNode.right = new TreeNode(val); + } + return; + } + parentNode = root; + if (root.val > val) recur(root.left, val); + if (root.val < val) recur(root.right, val); + } + let parentNode: TreeNode = root; + recur(root, val); + return root; +}; +``` + +> 迭代法 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + let curNode: TreeNode | null = root; + let parentNode: TreeNode = root; + while (curNode !== null) { + parentNode = curNode; + if (curNode.val > val) { + curNode = curNode.left + } else { + curNode = curNode.right; + } + } + if (parentNode.val > val) { + parentNode.left = new TreeNode(val); + } else { + parentNode.right = new TreeNode(val); + } + return root; +}; +``` + + + -----------------------

From 301dd3e13984a2d6de4711bc08417aa3bd2a1e8d Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 12 Mar 2022 00:15:06 +0800 Subject: [PATCH 199/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880450.?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0450.删除二叉搜索树中的节点.md | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 2e333530..cc29bea4 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -518,6 +518,70 @@ var deleteNode = function (root, key) { } ``` +## TypeScript + +> 递归法: + +```typescript +function deleteNode(root: TreeNode | null, key: number): TreeNode | null { + if (root === null) return null; + if (root.val === key) { + if (root.left === null && root.right === null) return null; + if (root.left === null) return root.right; + if (root.right === null) return root.left; + let curNode: TreeNode = root.right; + while (curNode.left !== null) { + curNode = curNode.left; + } + curNode.left = root.left; + return root.right; + } + if (root.val > key) root.left = deleteNode(root.left, key); + if (root.val < key) root.right = deleteNode(root.right, key); + return root; +}; +``` + +> 迭代法: + +```typescript +function deleteNode(root: TreeNode | null, key: number): TreeNode | null { + function removeTargetNode(root: TreeNode): TreeNode | null { + if (root.left === null && root.right === null) return null; + if (root.right === null) return root.left; + if (root.left === null) return root.right; + let curNode: TreeNode | null = root.right; + while (curNode.left !== null) { + curNode = curNode.left; + } + curNode.left = root.left; + return root.right; + } + let preNode: TreeNode | null = null, + curNode: TreeNode | null = root; + while (curNode !== null) { + if (curNode.val === key) break; + preNode = curNode; + if (curNode.val > key) { + curNode = curNode.left; + } else { + curNode = curNode.right; + } + } + if (curNode === null) return root; + if (preNode === null) { + // 删除头节点 + return removeTargetNode(curNode); + } + if (preNode.val > key) { + preNode.left = removeTargetNode(curNode); + } else { + preNode.right = removeTargetNode(curNode); + } + return root; +}; +``` + ----------------------- From 4549ca38bfbd438d2505f7925d6051ed146c53b4 Mon Sep 17 00:00:00 2001 From: Epoch <75031971+messenger1th@users.noreply.github.com> Date: Mon, 14 Mar 2022 13:33:40 +0800 Subject: [PATCH 200/257] =?UTF-8?q?Update=200151.=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=20=E5=90=8C=E7=90=86CPP=20=E7=89=88=E6=9C=AC2=E7=AE=80?= =?UTF-8?q?=E6=B4=81=E5=AE=9E=E7=8E=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 规范代码,优化留白。 同时添加详细注解, 并给出同理题目练习链接。 --- problems/0151.翻转字符串里的单词.md | 36 +++++++++++++++-------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 677a8f64..e7abd1d8 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -224,34 +224,36 @@ public: ```CPP //版本二: +//原理同版本1,更简洁实现。 class Solution { public: - void reverseWord(string& s,int start,int end){ //这个函数,Carl哥的要更清晰。 - for(int i=start;i<(end-start)/2+start;++i){ - swap(s[i],s[end-1-i+start]); + void reverse(string& s, int start, int end){ //翻转,区间写法:闭区间 [] + for (int i = start, j = end; i < j; i++, j--) { + swap(s[i], s[j]); } } - void trim(string& s){//去除所有空格并在相邻单词之间添加空格 - int slow = 0; - for(int i=0;i Date: Mon, 14 Mar 2022 18:58:24 +0800 Subject: [PATCH 201/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880669.?= =?UTF-8?q?=E4=BF=AE=E5=89=AA=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?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/0669.修剪二叉搜索树.md | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 15f6a040..385b2268 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -405,6 +405,56 @@ var trimBST = function (root,low,high) { } ``` +## TypeScript + +> 递归法 + +```typescript +function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + if (root === null) return null; + if (root.val < low) { + return trimBST(root.right, low, high); + } + if (root.val > high) { + return trimBST(root.left, low, high); + } + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + return root; +}; +``` + +> 迭代法 + +```typescript +function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + while (root !== null && (root.val < low || root.val > high)) { + if (root.val < low) { + root = root.right; + } else if (root.val > high) { + root = root.left; + } + } + let curNode: TreeNode | null = root; + while (curNode !== null) { + while (curNode.left !== null && curNode.left.val < low) { + curNode.left = curNode.left.right; + } + curNode = curNode.left; + } + curNode = root; + while (curNode !== null) { + while (curNode.right !== null && curNode.right.val > high) { + curNode.right = curNode.right.left; + } + curNode = curNode.right; + } + return root; +}; +``` + + + -----------------------
From e03a51264b584d83838a4847983b40ee1b7d7ddb Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 15 Mar 2022 00:08:01 +0800 Subject: [PATCH 202/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880108.?= =?UTF-8?q?=E5=B0=86=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E4=B8=BA=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0108.将有序数组转换为二叉搜索树.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 9e008e86..bd5915fd 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -251,7 +251,7 @@ class Solution { return root; } } -``` +``` 迭代: 左闭右闭 [left,right] ```java @@ -373,7 +373,24 @@ var sortedArrayToBST = function (nums) { }; ``` +## TypeScript + +```typescript +function sortedArrayToBST(nums: number[]): TreeNode | null { + function recur(nums: number[], left: number, right: number): TreeNode | null { + if (left > right) return null; + let mid: number = Math.floor((left + right) / 2); + const root: TreeNode = new TreeNode(nums[mid]); + root.left = recur(nums, left, mid - 1); + root.right = recur(nums, mid + 1, right); + return root; + } + return recur(nums, 0, nums.length - 1); +}; +``` + ## C + 递归 ```c struct TreeNode* traversal(int* nums, int left, int right) { From 56272922060f1ccff4196269dff1091e5315f2ad Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 16 Mar 2022 22:05:03 +0800 Subject: [PATCH 203/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880538.?= =?UTF-8?q?=E6=8A=8A=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC?= =?UTF-8?q?=E6=8D=A2=E4=B8=BA=E7=B4=AF=E5=8A=A0=E6=A0=91.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/0538.把二叉搜索树转换为累加树.md | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 1b07b803..37eb7d0f 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -312,5 +312,47 @@ struct TreeNode* convertBST(struct TreeNode* root){ } ``` +## TypeScript + +> 递归法 + +```typescript +function convertBST(root: TreeNode | null): TreeNode | null { + let pre: number = 0; + function recur(root: TreeNode | null): void { + if (root === null) return; + recur(root.right); + root.val += pre; + pre = root.val; + recur(root.left); + } + recur(root); + return root; +}; +``` + +> 迭代法 + +```typescript +function convertBST(root: TreeNode | null): TreeNode | null { + const helperStack: TreeNode[] = []; + let curNode: TreeNode | null = root; + let pre: number = 0; + while (curNode !== null || helperStack.length > 0) { + while (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.right; + } + curNode = helperStack.pop()!; + curNode.val += pre; + pre = curNode.val; + curNode = curNode.left; + } + return root; +}; +``` + + + -----------------------
From 1856401654174c3b50185471b9bc2888c04237c0 Mon Sep 17 00:00:00 2001 From: Speed <48878102+speedzjy@users.noreply.github.com> Date: Wed, 16 Mar 2022 22:26:46 +0800 Subject: [PATCH 204/257] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200134.=E5=8A=A0?= =?UTF-8?q?=E6=B2=B9=E7=AB=99.md=EF=BC=8C=20=E5=B0=86=E6=9A=B4=E5=8A=9B?= =?UTF-8?q?=E8=A7=A3=E6=B3=95=E4=BB=A3=E7=A0=81=E5=9D=97=E5=90=8E=E7=9A=84?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E7=94=B1O(n)=E6=94=B9=E4=B8=BAO(1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index ca95af67..1062a91c 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -78,7 +78,7 @@ public: ``` * 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n)$ +* 空间复杂度:$O(1)$ C++暴力解法在leetcode上提交也可以过。 From e1f3bdd973c88cada2a59dbc28fecbe0b798d246 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 17 Mar 2022 16:30:06 +0800 Subject: [PATCH 205/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880077.?= =?UTF-8?q?=E7=BB=84=E5=90=88.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0077.组合.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 2bd7a287..a1403c37 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -456,6 +456,27 @@ const combineHelper = (n, k, startIndex) => { } ``` +## TypeScript + +```typescript +function combine(n: number, k: number): number[][] { + let resArr: number[][] = []; + function backTracking(n: number, k: number, startIndex: number, tempArr: number[]): void { + if (tempArr.length === k) { + resArr.push(tempArr.slice()); + return; + } + for (let i = startIndex; i <= n - k + 1 + tempArr.length; i++) { + tempArr.push(i); + backTracking(n, k, i + 1, tempArr); + tempArr.pop(); + } + } + backTracking(n, k, 1, []); + return resArr; +}; +``` + ## Go From a90db6e830474a70dd445a77cef578627374ca5e Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Thu, 17 Mar 2022 13:38:45 -0500 Subject: [PATCH 206/257] =?UTF-8?q?0941.=E6=9C=89=E6=95=88=E7=9A=84?= =?UTF-8?q?=E5=B1=B1=E8=84=89=E6=95=B0=E7=BB=84=20python3=20=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=8F=8C=E6=8C=87=E9=92=88=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0941.有效的山脉数组 python3 从原方法更新到双指针方法 --- problems/0941.有效的山脉数组.md | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/problems/0941.有效的山脉数组.md b/problems/0941.有效的山脉数组.md index a2444cc1..4b7a978c 100644 --- a/problems/0941.有效的山脉数组.md +++ b/problems/0941.有效的山脉数组.md @@ -106,22 +106,15 @@ class Solution { ```python class Solution: def validMountainArray(self, arr: List[int]) -> bool: - if len(arr) < 3 : - return False - - i = 1 - flagIncrease = False # 上升 - flagDecrease = False # 下降 - - while i < len(arr) and arr[i-1] < arr[i]: - flagIncrease = True - i += 1 - - while i < len(arr) and arr[i-1] > arr[i]: - flagDecrease = True - i += 1 - - return i == len(arr) and flagIncrease and flagDecrease + left, right = 0, len(arr)-1 + + while left < len(arr)-1 and arr[left+1] > arr[left]: + left += 1 + + while right > 0 and arr[right-1] > arr[right]: + right -= 1 + + return left == right and right != 0 and left != len(arr)-1 ``` From a95b24a2290c72197e9107e38e91e11ffa92ef3d Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Thu, 17 Mar 2022 13:43:03 -0500 Subject: [PATCH 207/257] =?UTF-8?q?0225.=E7=94=A8=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=A0=88=20python3=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0225.用队列实现栈 python3 更新优化方法(只使用一个队列) --- problems/0225.用队列实现栈.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index c45917db..3457c4b3 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -354,6 +354,32 @@ class MyStack: return len(self.queue_in) == 0 ``` +优化,使用一个队列实现 +```python +class MyStack: + + def __init__(self): + self.que = deque() + + def push(self, x: int) -> None: + self.que.append(x) + + def pop(self) -> int: + if self.empty(): + return None + for i in range(len(self.que)-1): + self.que.append(self.que.popleft()) + return self.que.popleft() + + def top(self) -> int: + if self.empty(): + return None + return self.que[-1] + + def empty(self) -> bool: + return not self.que +``` + Go: From c77840639653808f528af05cd90ebef0c160cbf0 Mon Sep 17 00:00:00 2001 From: IcePigZDB Date: Sat, 19 Mar 2022 20:05:04 +0800 Subject: [PATCH 208/257] fix some small typo Signed-off-by: IcePigZDB --- problems/0020.有效的括号.md | 2 +- problems/0112.路径总和.md | 2 +- problems/0239.滑动窗口最大值.md | 2 +- problems/0377.组合总和Ⅳ.md | 2 +- problems/0647.回文子串.md | 4 ++-- problems/栈与队列理论基础.md | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 01fc7b93..7bb7f746 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -125,7 +125,7 @@ public: } }; ``` -技巧性的东西没有固定的学习方法,还是要多看多练,自己总灵活运用了。 +技巧性的东西没有固定的学习方法,还是要多看多练,自己灵活运用了。 ## 其他语言版本 diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5db36687..f80cf59c 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -212,7 +212,7 @@ public: }; ``` -如果大家完全理解了本地的递归方法之后,就可以顺便把leetcode上113. 路径总和ii做了。 +如果大家完全理解了本题的递归方法之后,就可以顺便把leetcode上113. 路径总和ii做了。 # 113. 路径总和ii diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index ce215a7e..f269450f 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -193,7 +193,7 @@ public: # 扩展 -大家貌似对单调队列 都有一些疑惑,首先要明确的是,题解中单调队列里的pop和push接口,仅适用于本题哈。单调队列不是一成不变的,而是不同场景不同写法,总之要保证队列里单调递减或递增的原则,所以叫做单调队列。 不要以为本地中的单调队列实现就是固定的写法哈。 +大家貌似对单调队列 都有一些疑惑,首先要明确的是,题解中单调队列里的pop和push接口,仅适用于本题哈。单调队列不是一成不变的,而是不同场景不同写法,总之要保证队列里单调递减或递增的原则,所以叫做单调队列。 不要以为本题中的单调队列实现就是固定的写法哈。 大家貌似对deque也有一些疑惑,C++中deque是stack和queue默认的底层实现容器(这个我们之前已经讲过啦),deque是可以两边扩展的,而且deque里元素并不是严格的连续分布的。 diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index 940d81b8..aaf27e61 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -127,7 +127,7 @@ public: ``` -C++测试用例有超过两个树相加超过int的数据,所以需要在if里加上dp[i] < INT_MAX - dp[i - num]。 +C++测试用例有两个数相加超过int的数据,所以需要在if里加上dp[i] < INT_MAX - dp[i - num]。 但java就不用考虑这个限制,java里的int也是四个字节吧,也有可能leetcode后台对不同语言的测试数据不一样。 diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index d9928b8f..913aec65 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -54,7 +54,7 @@ 当s[i]与s[j]相等时,这就复杂一些了,有如下三种情况 * 情况一:下标i 与 j相同,同一个字符例如a,当然是回文子串 -* 情况二:下标i 与 j相差为1,例如aa,也是文子串 +* 情况二:下标i 与 j相差为1,例如aa,也是回文子串 * 情况三:下标:i 与 j相差大于1的时候,例如cabac,此时s[i]与s[j]已经相同了,我们看i到j区间是不是回文子串就看aba是不是回文就可以了,那么aba的区间就是 i+1 与 j-1区间,这个区间是不是回文就看dp[i + 1][j - 1]是否为true。 以上三种情况分析完了,那么递归公式如下: @@ -178,7 +178,7 @@ public: 动态规划的空间复杂度是偏高的,我们再看一下双指针法。 -首先确定回文串,就是找中心然后想两边扩散看是不是对称的就可以了。 +首先确定回文串,就是找中心然后向两边扩散看是不是对称的就可以了。 **在遍历中心点的时候,要注意中心点有两种情况**。 diff --git a/problems/栈与队列理论基础.md b/problems/栈与队列理论基础.md index 44fcbdd5..8c76614f 100644 --- a/problems/栈与队列理论基础.md +++ b/problems/栈与队列理论基础.md @@ -15,7 +15,7 @@ 那么我这里在列出四个关于栈的问题,大家可以思考一下。以下是以C++为例,相信使用其他编程语言的同学也对应思考一下,自己使用的编程语言里栈和队列是什么样的。 1. C++中stack 是容器么? -2. 我们使用的stack是属于那个版本的STL? +2. 我们使用的stack是属于哪个版本的STL? 3. 我们使用的STL中stack是如何实现的? 4. stack 提供迭代器来遍历stack空间么? From 907204559fb56504a0035d70cbe478996152e8d3 Mon Sep 17 00:00:00 2001 From: IcePigZDB Date: Sat, 19 Mar 2022 20:15:24 +0800 Subject: [PATCH 209/257] =?UTF-8?q?=E5=AD=90=E9=9B=86II=20cpp=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81formate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: IcePigZDB --- problems/0090.子集II.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 16bd1f2c..d08707b4 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -87,7 +87,7 @@ class Solution { private: vector> result; vector path; - void backtracking(vector& nums, int startIndex, vector& used) { + void backtracking(vector& nums, int startIndex) { result.push_back(path); unordered_set uset; for (int i = startIndex; i < nums.size(); i++) { @@ -96,7 +96,7 @@ private: } uset.insert(nums[i]); path.push_back(nums[i]); - backtracking(nums, i + 1, used); + backtracking(nums, i + 1); path.pop_back(); } } @@ -105,9 +105,8 @@ public: vector> subsetsWithDup(vector& nums) { result.clear(); path.clear(); - vector used(nums.size(), false); sort(nums.begin(), nums.end()); // 去重需要排序 - backtracking(nums, 0, used); + backtracking(nums, 0); return result; } }; From 493d6ba16a1a2359ebfe110c338818de74632476 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 20 Mar 2022 20:54:32 +0800 Subject: [PATCH 210/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880077.?= =?UTF-8?q?=E7=BB=84=E5=90=88=E4=BC=98=E5=8C=96.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- node_modules/.yarn-integrity | 10 ++++++++++ problems/0077.组合优化.md | 22 ++++++++++++++++++++++ yarn.lock | 4 ++++ 3 files changed, 36 insertions(+) create mode 100644 node_modules/.yarn-integrity create mode 100644 yarn.lock diff --git a/node_modules/.yarn-integrity b/node_modules/.yarn-integrity new file mode 100644 index 00000000..29e4357c --- /dev/null +++ b/node_modules/.yarn-integrity @@ -0,0 +1,10 @@ +{ + "systemParams": "win32-x64-83", + "modulesFolders": [], + "flags": [], + "linkedModules": [], + "topLevelPatterns": [], + "lockfileEntries": {}, + "files": [], + "artifacts": {} +} \ No newline at end of file diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 81b4304c..94608ec1 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -240,7 +240,29 @@ var combine = function(n, k) { }; ``` +TypeScript: + +```typescript +function combine(n: number, k: number): number[][] { + let resArr: number[][] = []; + function backTracking(n: number, k: number, startIndex: number, tempArr: number[]): void { + if (tempArr.length === k) { + resArr.push(tempArr.slice()); + return; + } + for (let i = startIndex; i <= n - k + 1 + tempArr.length; i++) { + tempArr.push(i); + backTracking(n, k, i + 1, tempArr); + tempArr.pop(); + } + } + backTracking(n, k, 1, []); + return resArr; +}; +``` + C: + ```c int* path; int pathTop; diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 00000000..3ff608ae --- /dev/null +++ b/yarn.lock @@ -0,0 +1,4 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + From 8ad12370b69a4b37f3baffe8e1102e82c394ac4a Mon Sep 17 00:00:00 2001 From: "Neil.Liu" <88214924@qq.com> Date: Sun, 20 Mar 2022 22:32:34 +0800 Subject: [PATCH 211/257] =?UTF-8?q?Update=200332.=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 58 +++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 01f81c4d..041a7f03 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -342,6 +342,64 @@ class Solution: return path ``` +### Go +```go +type pair struct { + target string + visited bool +} +type pairs []*pair + +func (p pairs) Len() int { + return len(p) +} +func (p pairs) Swap(i, j int) { + p[i], p[j] = p[j], p[i] +} +func (p pairs) Less(i, j int) bool { + return p[i].target < p[j].target +} + +func findItinerary(tickets [][]string) []string { + result := []string{} + // map[出发机场] pair{目的地,是否被访问过} + targets := make(map[string]pairs) + for _, ticket := range tickets { + if targets[ticket[0]] == nil { + targets[ticket[0]] = make(pairs, 0) + } + targets[ticket[0]] = append(targets[ticket[0]], &pair{target: ticket[1], visited: false}) + } + for k, _ := range targets { + sort.Sort(targets[k]) + } + result = append(result, "JFK") + var backtracking func() bool + backtracking = func() bool { + if len(tickets)+1 == len(result) { + return true + } + // 取出起飞航班对应的目的地 + for _, pair := range targets[result[len(result)-1]] { + if pair.visited == false { + result = append(result, pair.target) + pair.visited = true + if backtracking() { + return true + } + result = result[:len(result)-1] + pair.visited = false + } + } + return false + } + + backtracking() + + return result +} +``` + ### C语言 ```C From 21f6068e2e3fd0c3d40971df3c0ea3b35a9ec248 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 20 Mar 2022 23:24:57 +0800 Subject: [PATCH 212/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880216.?= =?UTF-8?q?=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8CIII.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0216.组合总和III.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 0bb42192..32b1347e 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -396,6 +396,30 @@ var combinationSum3 = function(k, n) { }; ``` +## TypeScript + +```typescript +function combinationSum3(k: number, n: number): number[][] { + const resArr: number[][] = []; + function backTracking(k: number, n: number, sum: number, startIndex: number, tempArr: number[]): void { + if (sum > n) return; + if (tempArr.length === k) { + if (sum === n) { + resArr.push(tempArr.slice()); + } + return; + } + for (let i = startIndex; i <= 9 - (k - tempArr.length) + 1; i++) { + tempArr.push(i); + backTracking(k, n, sum + i, i + 1, tempArr); + tempArr.pop(); + } + } + backTracking(k, n, 0, 1, []); + return resArr; +}; +``` + ## C ```c From 82feee15424aa110e5d30b333ea3c0a83245b3c2 Mon Sep 17 00:00:00 2001 From: dcj_hp <294487055@qq.com> Date: Mon, 21 Mar 2022 12:04:13 +0800 Subject: [PATCH 213/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20647.=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E5=AD=90=E4=B8=B2=20=E6=96=87=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0647.回文子串.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index d9928b8f..739146f1 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -54,7 +54,7 @@ 当s[i]与s[j]相等时,这就复杂一些了,有如下三种情况 * 情况一:下标i 与 j相同,同一个字符例如a,当然是回文子串 -* 情况二:下标i 与 j相差为1,例如aa,也是文子串 +* 情况二:下标i 与 j相差为1,例如aa,也是回文子串 * 情况三:下标:i 与 j相差大于1的时候,例如cabac,此时s[i]与s[j]已经相同了,我们看i到j区间是不是回文子串就看aba是不是回文就可以了,那么aba的区间就是 i+1 与 j-1区间,这个区间是不是回文就看dp[i + 1][j - 1]是否为true。 以上三种情况分析完了,那么递归公式如下: From c408f7babc6f944cde16e51916c2741c5ab8a43e Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Tue, 22 Mar 2022 09:29:32 +0800 Subject: [PATCH 214/257] Update --- problems/0042.接雨水.md | 10 +++++----- problems/0077.组合.md | 4 ++-- problems/0337.打家劫舍III.md | 10 +++++----- problems/0416.分割等和子集.md | 10 ++++------ problems/前序/ACM模式如何构建二叉树.md | 9 --------- .../BAT级别技术面试流程和注意事项都在这里了.md | 9 +-------- .../On的算法居然超时了,此时的n究竟是多大?.md | 18 ++++++----------- problems/前序/上海互联网公司总结.md | 8 -------- .../什么是核心代码模式,什么又是ACM模式?.md | 8 +------- problems/前序/代码风格.md | 17 +--------------- .../关于时间复杂度,你不知道的都在这里!.md | 8 +------- .../前序/关于空间复杂度,可能有几个疑问?.md | 8 -------- ...了这么多题,你了解自己代码的内存消耗么?.md | 9 +-------- .../前序/力扣上的代码想在本地编译运行?.md | 8 +------- problems/前序/北京互联网公司总结.md | 11 ++-------- problems/前序/广州互联网公司总结.md | 10 ++-------- problems/前序/成都互联网公司总结.md | 12 ++--------- problems/前序/杭州互联网公司总结.md | 11 ++-------- problems/前序/深圳互联网公司总结.md | 10 ++-------- problems/前序/程序员写文档工具.md | 12 +++-------- problems/前序/程序员简历.md | 13 +----------- .../前序/递归算法的时间与空间复杂度分析.md | 8 -------- ...一道面试题目,讲一讲递归算法的时间复杂度!.md | 10 ---------- problems/回溯总结.md | 20 +++++++++---------- problems/知识星球精选/HR特意刁难非科班.md | 4 ++-- problems/知识星球精选/HR面注意事项.md | 6 +++--- problems/知识星球精选/offer对比-决赛圈.md | 4 ++-- .../知识星球精选/offer总决赛,何去何从.md | 4 ++-- problems/知识星球精选/offer的选择.md | 4 ++-- problems/知识星球精选/不一样的七夕.md | 4 ++-- problems/知识星球精选/不喜欢写代码怎么办.md | 2 +- problems/知识星球精选/不少录友想放弃秋招.md | 8 ++++---- problems/知识星球精选/专业技能可以这么写.md | 4 ++-- .../知识星球精选/入职后担心代码能力跟不上.md | 4 ++-- problems/知识星球精选/关于实习大家的疑问.md | 4 ++-- problems/知识星球精选/关于提前批的一些建议.md | 4 ++-- problems/知识星球精选/写简历的一些问题.md | 4 ++-- .../知识星球精选/初入大三选择考研VS工作.md | 4 ++-- problems/知识星球精选/刷力扣用不用库函数.md | 4 ++-- problems/知识星球精选/刷题攻略要刷两遍.md | 4 ++-- problems/知识星球精选/博士转行计算机.md | 4 ++-- problems/知识星球精选/合适自己的就是最好的.md | 6 +++--- problems/知识星球精选/备战2022届秋招.md | 4 ++-- problems/知识星球精选/大厂新人培养体系.md | 4 ++-- problems/知识星球精选/天下乌鸦一般黑.md | 4 ++-- .../知识星球精选/如何权衡实习与秋招复习.md | 4 ++-- problems/知识星球精选/客三消.md | 6 +++--- .../知识星球精选/技术不好如何选择技术方向.md | 4 ++-- problems/知识星球精选/提前批已经开始了.md | 4 ++-- .../知识星球精选/秋招下半场依然没offer.md | 12 +++++------ problems/知识星球精选/秋招开奖.md | 4 ++-- problems/知识星球精选/秋招总结1.md | 4 ++-- problems/知识星球精选/秋招总结2.md | 4 ++-- problems/知识星球精选/秋招总结3.md | 4 ++-- problems/知识星球精选/秋招的上半场.md | 4 ++-- .../知识星球精选/秋招进行中的迷茫与焦虑.md | 4 ++-- problems/知识星球精选/英语到底重不重要.md | 4 ++-- problems/知识星球精选/要不要考研.md | 4 ++-- problems/知识星球精选/逼签.md | 2 +- problems/知识星球精选/非科班2021秋招总结.md | 4 ++-- problems/知识星球精选/非科班的困扰.md | 4 ++-- problems/知识星球精选/面试中发散性问题.md | 4 ++-- 62 files changed, 135 insertions(+), 284 deletions(-) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index 55f80a54..75152eb7 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -365,7 +365,7 @@ public: ## 其他语言版本 -Java: +### Java: 双指针法 ```java @@ -468,7 +468,7 @@ class Solution { } ``` -Python: +### Python: 双指针法 ```python3 @@ -575,7 +575,7 @@ class Solution: ``` -Go: +### Go ```go func trap(height []int) int { @@ -642,7 +642,7 @@ func min(a,b int)int{ -JavaScript: +### JavaScript: ```javascript //双指针 @@ -744,7 +744,7 @@ var trap = function(height) { }; ``` -C: +### C: 一种更简便的双指针方法: diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 2bd7a287..e582daf6 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -423,8 +423,8 @@ class Solution: if len(path) == k: res.append(path[:]) return - for i in range(startIndex,n - (k - len(path)) + 2): #优化的地方 - path.append(i) #处理节点 + for i in range(startIndex,n-(k-len(path))+2): #优化的地方 + path.append(i) #处理节点 backtrack(n,k,i+1) #递归 path.pop() #回溯,撤销处理的节点 backtrack(n,k,1) diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index ecd31d1b..a4d8f6b2 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -216,7 +216,7 @@ public: ## 其他语言版本 -Java: +### Java ```Java class Solution { // 1.递归去偷,超时 @@ -284,7 +284,7 @@ class Solution { } ``` -Python: +### Python > 暴力递归 @@ -367,7 +367,7 @@ class Solution: return (val1, val2) ``` -Go: +### Go 动态规划 @@ -402,7 +402,7 @@ func robTree(cur *TreeNode) []int { } ``` -JavaScript: +### JavaScript > 动态规划 @@ -429,7 +429,7 @@ const rob = root => { }; ``` -Go: +### Go ```go // 打家劫舍Ⅲ 动态规划 // 时间复杂度O(n) 空间复杂度O(logn) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index 9da1f8d5..4b26d188 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -127,9 +127,9 @@ for(int i = 0; i < nums.size(); i++) { 5. 举例推导dp数组 -dp[i]的数值一定是小于等于i的。 +dp[j]的数值一定是小于等于j的。 -**如果dp[i] == i 说明,集合中的子集总和正好可以凑成总和i,理解这一点很重要。** +**如果dp[j] == j 说明,集合中的子集总和正好可以凑成总和j,理解这一点很重要。** 用例1,输入[1,5,11,5] 为例,如图: @@ -168,8 +168,8 @@ public: }; ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n)$,虽然dp数组大小为一个常数,但是大常数 +* 时间复杂度:O(n^2) +* 空间复杂度:O(n),虽然dp数组大小为一个常数,但是大常数 ## 总结 @@ -180,8 +180,6 @@ public: 看代码的话,就可以发现,基本就是按照01背包的写法来的。 - - ## 其他语言版本 diff --git a/problems/前序/ACM模式如何构建二叉树.md b/problems/前序/ACM模式如何构建二叉树.md index 28c4b6f7..bd2e9780 100644 --- a/problems/前序/ACM模式如何构建二叉树.md +++ b/problems/前序/ACM模式如何构建二叉树.md @@ -1,13 +1,4 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - # 力扣上如何自己构造二叉树输入用例? 经常有录友问,二叉树的题目中输入用例在ACM模式下应该怎么构造呢? diff --git a/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md b/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md index 6678860d..27940f1b 100644 --- a/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md +++ b/problems/前序/BAT级别技术面试流程和注意事项都在这里了.md @@ -1,12 +1,5 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- +# 大厂技术面试流程和注意事项 大型互联网企业一般通过几轮技术面试来考察大家的各项能力,一般流程如下: diff --git a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md index 5257ceb9..20a48e19 100644 --- a/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/前序/On的算法居然超时了,此时的n究竟是多大?.md @@ -1,18 +1,12 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+# On的算法居然超时了,此时的n究竟是多大? 一些同学可能对计算机运行的速度还没有概念,就是感觉计算机运行速度应该会很快,那么在leetcode上做算法题目的时候为什么会超时呢? 计算机究竟1s可以执行多少次操作呢? 接下来探讨一下这个问题。 -# 超时是怎么回事 +## 超时是怎么回事 ![程序超时](https://img-blog.csdnimg.cn/20200729112716117.png) @@ -24,7 +18,7 @@ 如果n的规模已经足够让$O(n)$的算法运行时间超过了1s,就应该考虑log(n)的解法了。 -# 从硬件配置看计算机的性能 +## 从硬件配置看计算机的性能 计算机的运算速度主要看CPU的配置,以2015年MacPro为例,CPU配置:2.7 GHz Dual-Core Intel Core i5 。 @@ -43,7 +37,7 @@ 所以我们的程序在计算机上究竟1s真正能执行多少次操作呢? -# 做个测试实验 +## 做个测试实验 在写测试程序测1s内处理多大数量级数据的时候,有三点需要注意: @@ -152,7 +146,7 @@ $O(n\log n)$的算法,1s内大概计算机可以运行 2 * (10^7)次计算, 至于 $O(\log n)$ 和 $O(n^3)$ 等等这些时间复杂度在1s内可以处理的多大的数据规模,大家可以自己写一写代码去测一下了。 -# 完整测试代码 +## 完整测试代码 ```CPP #include @@ -264,7 +258,7 @@ public class TimeComplexity { } ``` -# 总结 +## 总结 本文详细分析了在leetcode上做题程序为什么会有超时,以及从硬件配置上大体知道CPU的执行速度,然后亲自做一个实验来看看$O(n)$的算法,跑一秒钟,这个n究竟是做大,最后给出不同时间复杂度,一秒内可以运算出来的n的大小。 diff --git a/problems/前序/上海互联网公司总结.md b/problems/前序/上海互联网公司总结.md index ffcbe77b..6309ef58 100644 --- a/problems/前序/上海互联网公司总结.md +++ b/problems/前序/上海互联网公司总结.md @@ -1,11 +1,3 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- # 上海互联网公司总结 diff --git a/problems/前序/什么是核心代码模式,什么又是ACM模式?.md b/problems/前序/什么是核心代码模式,什么又是ACM模式?.md index 54c5b6ec..0b9d230f 100644 --- a/problems/前序/什么是核心代码模式,什么又是ACM模式?.md +++ b/problems/前序/什么是核心代码模式,什么又是ACM模式?.md @@ -1,11 +1,5 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+# 什么是核心代码模式,什么又是ACM模式? 现在很多企业都在牛客上进行面试,**很多录友和我反馈说搞不懂牛客上输入代码的ACM模式**。 diff --git a/problems/前序/代码风格.md b/problems/前序/代码风格.md index b48665e5..4ab94a51 100644 --- a/problems/前序/代码风格.md +++ b/problems/前序/代码风格.md @@ -1,13 +1,3 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - - # 看了这么多代码,谈一谈代码风格! @@ -142,11 +132,6 @@ Google规范是 大括号和 控制语句保持同一行的,我个人也很认 就酱,以后我还会陆续分享,关于代码,求职,学习工作之类的内容。 - - - ----------------------- -* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) -* B站视频:[代码随想录](https://space.bilibili.com/525438321) -* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +
diff --git a/problems/前序/关于时间复杂度,你不知道的都在这里!.md b/problems/前序/关于时间复杂度,你不知道的都在这里!.md index 478b82e4..b2acb7dd 100644 --- a/problems/前序/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/前序/关于时间复杂度,你不知道的都在这里!.md @@ -1,11 +1,5 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+# 关于时间复杂度,你不知道的都在这里! 相信每一位录友都接触过时间复杂度,但又对时间复杂度的认识处于一种朦胧的状态,所以是时候对时间复杂度来一个深度的剖析了。 diff --git a/problems/前序/关于空间复杂度,可能有几个疑问?.md b/problems/前序/关于空间复杂度,可能有几个疑问?.md index d49b42a2..162dfe96 100644 --- a/problems/前序/关于空间复杂度,可能有几个疑问?.md +++ b/problems/前序/关于空间复杂度,可能有几个疑问?.md @@ -1,11 +1,3 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- # 空间复杂度分析 diff --git a/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md b/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md index 0364fc8b..f4aa4b6e 100644 --- a/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md +++ b/problems/前序/刷了这么多题,你了解自己代码的内存消耗么?.md @@ -1,13 +1,6 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- +# 刷了这么多题,你了解自己代码的内存消耗么? 理解代码的内存消耗,最关键是要知道自己所用编程语言的内存管理。 diff --git a/problems/前序/力扣上的代码想在本地编译运行?.md b/problems/前序/力扣上的代码想在本地编译运行?.md index dca6eec3..bcef3886 100644 --- a/problems/前序/力扣上的代码想在本地编译运行?.md +++ b/problems/前序/力扣上的代码想在本地编译运行?.md @@ -1,10 +1,4 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+# 力扣上的代码想在本地编译运行? 很多录友都问过我一个问题,就是力扣上的代码如何在本地编译运行? diff --git a/problems/前序/北京互联网公司总结.md b/problems/前序/北京互联网公司总结.md index 02a877b7..a10cab06 100644 --- a/problems/前序/北京互联网公司总结.md +++ b/problems/前序/北京互联网公司总结.md @@ -1,15 +1,8 @@ -

- - - - -

+# 北京互联网公司总结 +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- -# 北京互联网公司总结 - **个人总结难免有所疏忽,欢迎大家补充,公司好坏没有排名哈!** 如果要在北京找工作,这份list可以作为一个大纲,寻找自己合适的公司。 diff --git a/problems/前序/广州互联网公司总结.md b/problems/前序/广州互联网公司总结.md index e83fcd2b..b8b1641b 100644 --- a/problems/前序/广州互联网公司总结.md +++ b/problems/前序/广州互联网公司总结.md @@ -1,14 +1,8 @@ -

- - - - -

+# 广州互联网公司总结 +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-# 广州互联网公司总结 - **个人总结难免有所疏忽,欢迎大家补充,公司好坏没有排名哈!** ## 一线互联网 diff --git a/problems/前序/成都互联网公司总结.md b/problems/前序/成都互联网公司总结.md index 7964f23c..f6a575f6 100644 --- a/problems/前序/成都互联网公司总结.md +++ b/problems/前序/成都互联网公司总结.md @@ -1,15 +1,7 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - - # 成都互联网公司总结 +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ **排名不分先后,个人总结难免有所疏漏,欢迎补充!** diff --git a/problems/前序/杭州互联网公司总结.md b/problems/前序/杭州互联网公司总结.md index 029ee380..6154cfe5 100644 --- a/problems/前序/杭州互联网公司总结.md +++ b/problems/前序/杭州互联网公司总结.md @@ -1,15 +1,8 @@ -

- - - - -

+# 杭州互联网公司总结 +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- -# 杭州互联网公司总结 - **个人总结难免有所疏忽,欢迎大家补充,公司好坏没有排名哈!** ## 一线互联网 diff --git a/problems/前序/深圳互联网公司总结.md b/problems/前序/深圳互联网公司总结.md index 61bd52e8..3d548abb 100644 --- a/problems/前序/深圳互联网公司总结.md +++ b/problems/前序/深圳互联网公司总结.md @@ -1,14 +1,8 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- # 深圳互联网公司总结 +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

+ **个人总结难免有所疏忽,欢迎大家补充,公司好坏没有排名哈!** ## 一线互联网 diff --git a/problems/前序/程序员写文档工具.md b/problems/前序/程序员写文档工具.md index 5504ae7a..a2f6ee3b 100644 --- a/problems/前序/程序员写文档工具.md +++ b/problems/前序/程序员写文档工具.md @@ -1,16 +1,10 @@ -

- - - - -

+ +# 程序员应该用什么用具来写文档? +

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- -# 程序员应该用什么用具来写文档? - Carl平时写东西,都是统一使用markdown,包括题解啊,笔记啊,所以这里给大家安利一波markdown对程序员的重要性! 程序员为什么要学习markdown呢? diff --git a/problems/前序/程序员简历.md b/problems/前序/程序员简历.md index 522fc5f7..e64f547a 100644 --- a/problems/前序/程序员简历.md +++ b/problems/前序/程序员简历.md @@ -1,16 +1,5 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - - # 程序员的简历应该这么写!!(附简历模板) - Carl校招社招都拿过大厂的offer,同时也看过很多应聘者的简历,这里把自己总结的简历技巧以及常见问题给大家梳理一下。 ## 简历篇幅 @@ -116,7 +105,7 @@ Carl校招社招都拿过大厂的offer,同时也看过很多应聘者的简 ![简历模板](https://img-blog.csdnimg.cn/20200803175538158.png) -这里是简历模板中Markdown的代码:https://github.com/youngyangyang04/Markdown-Resume-Template ,可以fork到自己Github仓库上,按照这个模板来修改自己的简历。 +这里是简历模板中Markdown的代码:[https://github.com/youngyangyang04/Markdown-Resume-Template](https://github.com/youngyangyang04/Markdown-Resume-Template) ,可以fork到自己Github仓库上,按照这个模板来修改自己的简历。 **Word版本的简历,大家可以在公众号「代码随想录」后台回复:简历模板,就可以获取!** diff --git a/problems/前序/递归算法的时间与空间复杂度分析.md b/problems/前序/递归算法的时间与空间复杂度分析.md index 914cccfd..3c0d219c 100644 --- a/problems/前序/递归算法的时间与空间复杂度分析.md +++ b/problems/前序/递归算法的时间与空间复杂度分析.md @@ -1,11 +1,3 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- # 递归算法的时间与空间复杂度分析! diff --git a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md index 849a025d..12af4dd8 100644 --- a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md +++ b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md @@ -1,13 +1,3 @@ -

- - - - -

-

欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

- - - # 通过一道面试题目,讲一讲递归算法的时间复杂度! diff --git a/problems/回溯总结.md b/problems/回溯总结.md index 671e0a4e..bd0db575 100644 --- a/problems/回溯总结.md +++ b/problems/回溯总结.md @@ -380,24 +380,24 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所 以下在计算空间复杂度的时候我都把系统栈(不是数据结构里的栈)所占空间算进去。 子集问题分析: -* 时间复杂度:$O(2^n)$,因为每一个元素的状态无外乎取与不取,所以时间复杂度为$O(2^n)$ -* 空间复杂度:$O(n)$,递归深度为n,所以系统栈所用空间为$O(n)$,每一层递归所用的空间都是常数级别,注意代码里的result和path都是全局变量,就算是放在参数里,传的也是引用,并不会新申请内存空间,最终空间复杂度为$O(n)$ +* 时间复杂度:O(2^n),因为每一个元素的状态无外乎取与不取,所以时间复杂度为$O(2^n)$ +* 空间复杂度:O(n),递归深度为n,所以系统栈所用空间为$O(n)$,每一层递归所用的空间都是常数级别,注意代码里的result和path都是全局变量,就算是放在参数里,传的也是引用,并不会新申请内存空间,最终空间复杂度为$O(n)$ 排列问题分析: -* 时间复杂度:$O(n!)$,这个可以从排列的树形图中很明显发现,每一层节点为n,第二层每一个分支都延伸了n-1个分支,再往下又是n-2个分支,所以一直到叶子节点一共就是 n * n-1 * n-2 * ..... 1 = n!。 -* 空间复杂度:$O(n)$,和子集问题同理。 +* 时间复杂度:O(n!),这个可以从排列的树形图中很明显发现,每一层节点为n,第二层每一个分支都延伸了n-1个分支,再往下又是n-2个分支,所以一直到叶子节点一共就是 n * n-1 * n-2 * ..... 1 = n!。 +* 空间复杂度:O(n),和子集问题同理。 组合问题分析: -* 时间复杂度:$O(2^n)$,组合问题其实就是一种子集的问题,所以组合问题最坏的情况,也不会超过子集问题的时间复杂度。 -* 空间复杂度:$O(n)$,和子集问题同理。 +* 时间复杂度:O(2^n),组合问题其实就是一种子集的问题,所以组合问题最坏的情况,也不会超过子集问题的时间复杂度。 +* 空间复杂度:O(n),和子集问题同理。 N皇后问题分析: -* 时间复杂度:$O(n!)$ ,其实如果看树形图的话,直觉上是$O(n^n)$,但皇后之间不能见面所以在搜索的过程中是有剪枝的,最差也就是O(n!),n!表示n * (n-1) * .... * 1。 -* 空间复杂度:$O(n)$,和子集问题同理。 +* 时间复杂度:O(n!) ,其实如果看树形图的话,直觉上是$O(n^n)$,但皇后之间不能见面所以在搜索的过程中是有剪枝的,最差也就是O(n!),n!表示n * (n-1) * .... * 1。 +* 空间复杂度:O(n),和子集问题同理。 解数独问题分析: -* 时间复杂度:$O(9^m)$ , m是'.'的数目。 -* 空间复杂度:$O(n^2)$,递归的深度是n^2 +* 时间复杂度:O(9^m) , m是'.'的数目。 +* 空间复杂度:O(n^2),递归的深度是n^2 **一般说道回溯算法的复杂度,都说是指数级别的时间复杂度,这也算是一个概括吧!** diff --git a/problems/知识星球精选/HR特意刁难非科班.md b/problems/知识星球精选/HR特意刁难非科班.md index c59debf2..d5d39fe3 100644 --- a/problems/知识星球精选/HR特意刁难非科班.md +++ b/problems/知识星球精选/HR特意刁难非科班.md @@ -1,6 +1,6 @@

- + @@ -8,7 +8,7 @@ 不少录友都是非科班转程序员,或者进军互联网的,但有一些HR在HR面的时候特意刁难大家。 -正如[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,这位录友所遭受的情景。 +正如[知识星球](https://programmercarl.com/other/kstar.html)里,这位录友所遭受的情景。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211006230202.png) diff --git a/problems/知识星球精选/HR面注意事项.md b/problems/知识星球精选/HR面注意事项.md index 6a0a26f1..5dba672c 100644 --- a/problems/知识星球精选/HR面注意事项.md +++ b/problems/知识星球精选/HR面注意事项.md @@ -1,12 +1,12 @@

- + # HR面注意事项 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里已经有一些录友开始准备HR面。 +[知识星球](https://programmercarl.com/other/kstar.html)里已经有一些录友开始准备HR面。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210807155107.png) @@ -86,4 +86,4 @@ HR朋友的回答是:你不说真相,我会认为你可能对技术有追求 --------------- -加入「代码随想录」知识星球,[点击这里](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) +加入「代码随想录」知识星球,[点击这里](https://programmercarl.com/other/kstar.html) diff --git a/problems/知识星球精选/offer对比-决赛圈.md b/problems/知识星球精选/offer对比-决赛圈.md index 1f91730f..081ae5ec 100644 --- a/problems/知识星球精选/offer对比-决赛圈.md +++ b/problems/知识星球精选/offer对比-决赛圈.md @@ -1,5 +1,5 @@

- + @@ -7,7 +7,7 @@ 秋招已经结束了,该开奖的差不多都陆续开奖了,很多录友的也进入了offer决赛圈。 -我每天都在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,回答十几个offer对比的问题,我也是结合自己过来人的经验给大家做做分析,我也选几个案例,在公众号上也给大家分享一下,希望对大家有所启发。 +我每天都在[知识星球](https://programmercarl.com/other/kstar.html)里,回答十几个offer对比的问题,我也是结合自己过来人的经验给大家做做分析,我也选几个案例,在公众号上也给大家分享一下,希望对大家有所启发。 以下是知识星球里的部分问答: diff --git a/problems/知识星球精选/offer总决赛,何去何从.md b/problems/知识星球精选/offer总决赛,何去何从.md index 01745ae3..e22c5d4a 100644 --- a/problems/知识星球精选/offer总决赛,何去何从.md +++ b/problems/知识星球精选/offer总决赛,何去何从.md @@ -1,12 +1,12 @@

- + # offer总决赛,何去何从! -最近在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)上,给至少300位录友做了offer选择,准对大家的情况,结合我的经验做一做分析。 +最近在[知识星球](https://programmercarl.com/other/kstar.html)上,给至少300位录友做了offer选择,准对大家的情况,结合我的经验做一做分析。 希望可以给大家带来不一样的分析视角,帮大家少走弯路。 diff --git a/problems/知识星球精选/offer的选择.md b/problems/知识星球精选/offer的选择.md index b9b40dea..106bc5f8 100644 --- a/problems/知识星球精选/offer的选择.md +++ b/problems/知识星球精选/offer的选择.md @@ -1,6 +1,6 @@

- + @@ -10,7 +10,7 @@ 不过大部分同学应该拿到的是 两个大厂offer,或者说拿到两个小厂offer,还要考虑岗位,业务,公司前景,那么就要纠结如何选择了。 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,我已经给很多录友提供了选择offer的建议,这里也分享出来,希望对大家在选择offer上有所启发。 +在[知识星球](https://programmercarl.com/other/kstar.html)里,我已经给很多录友提供了选择offer的建议,这里也分享出来,希望对大家在选择offer上有所启发。 ## 保研与工作 diff --git a/problems/知识星球精选/不一样的七夕.md b/problems/知识星球精选/不一样的七夕.md index a670e078..40d15ecd 100644 --- a/problems/知识星球精选/不一样的七夕.md +++ b/problems/知识星球精选/不一样的七夕.md @@ -1,11 +1,11 @@

- + # 特殊的七夕 -昨天在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)发了一个状态: +昨天在[知识星球](https://programmercarl.com/other/kstar.html)发了一个状态: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210815084126.png) diff --git a/problems/知识星球精选/不喜欢写代码怎么办.md b/problems/知识星球精选/不喜欢写代码怎么办.md index 9bc624bb..84d372f0 100644 --- a/problems/知识星球精选/不喜欢写代码怎么办.md +++ b/problems/知识星球精选/不喜欢写代码怎么办.md @@ -1,7 +1,7 @@ # 看到代码就抵触!怎么办? -最近在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,看到了不少录友,其实是不喜欢写代码,看到 哪些八股文都是很抵触的。 +最近在[知识星球](https://programmercarl.com/other/kstar.html)里,看到了不少录友,其实是不喜欢写代码,看到 哪些八股文都是很抵触的。 其实是一个普遍现象,我在星球里分享了一下,我对这一情况的一些想法。 diff --git a/problems/知识星球精选/不少录友想放弃秋招.md b/problems/知识星球精选/不少录友想放弃秋招.md index 721a9313..81c99503 100644 --- a/problems/知识星球精选/不少录友想放弃秋招.md +++ b/problems/知识星球精选/不少录友想放弃秋招.md @@ -1,5 +1,5 @@

- + @@ -7,7 +7,7 @@ 马上就要九月份了,互联网大厂的秋招的序幕早已拉开。 -发现[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里有一部分录友想放弃秋招,直接准备明年的春招,估计关注公众号的录友也有不少有这种想法的。 +发现[知识星球](https://programmercarl.com/other/kstar.html)里有一部分录友想放弃秋招,直接准备明年的春招,估计关注公众号的录友也有不少有这种想法的。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210813103515.png) @@ -50,7 +50,7 @@ 所以也给明年找工作的录友们(2023届)提一个醒,现在就要系统性的准备起来了,因为明年春季实习招聘 是一个很好的进大厂的机会,剩下的时间也不是很多了。 -来看看[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,一位准大三的录友准备的情况 +来看看[知识星球](https://programmercarl.com/other/kstar.html)里,一位准大三的录友准备的情况 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/星球大三.jpg) @@ -60,7 +60,7 @@ **我已经预感到 这两位 等到秋招的时候就是稳稳的offer收割机**。 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)还有很多已经开始提前准备,或者看了 星球发文状态就开始着手准备的录友了。 +[知识星球](https://programmercarl.com/other/kstar.html)还有很多已经开始提前准备,或者看了 星球发文状态就开始着手准备的录友了。 所以 **所谓的大牛,都是 很早就规划自己要学的东西,很早就开始向过来人请教应该如何找工作,很早就知道自己应该学哪些技术,看哪些书, 这样等到找工作的时候,才是剑锋出鞘的时候**。 diff --git a/problems/知识星球精选/专业技能可以这么写.md b/problems/知识星球精选/专业技能可以这么写.md index dd616713..a1b7ba3a 100644 --- a/problems/知识星球精选/专业技能可以这么写.md +++ b/problems/知识星球精选/专业技能可以这么写.md @@ -1,5 +1,5 @@

- + @@ -8,7 +8,7 @@ # 你简历里的「专业技能」写的够专业么? -其实我几乎每天都要看一些简历,有一些写的不错的,我都会在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里分享一下。 +其实我几乎每天都要看一些简历,有一些写的不错的,我都会在[知识星球](https://programmercarl.com/other/kstar.html)里分享一下。 ![](https://code-thinking-1253855093.cos.ap-guangzhou.myqcloud.com/pics/20210626172902.png) 这次呢,我再专门说一说简历中的【专业技能】这一栏应该怎么写。 diff --git a/problems/知识星球精选/入职后担心代码能力跟不上.md b/problems/知识星球精选/入职后担心代码能力跟不上.md index c2704525..58b8c32c 100644 --- a/problems/知识星球精选/入职后担心代码能力跟不上.md +++ b/problems/知识星球精选/入职后担心代码能力跟不上.md @@ -1,12 +1,12 @@

- + # 入职后担心代码能力跟不上 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)上,很多录友已经担心自己去了公司工作以后,代码能力跟不上,会压力很大。 +在[知识星球](https://programmercarl.com/other/kstar.html)上,很多录友已经担心自己去了公司工作以后,代码能力跟不上,会压力很大。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211031202952.png) diff --git a/problems/知识星球精选/关于实习大家的疑问.md b/problems/知识星球精选/关于实习大家的疑问.md index 5d4e695b..88de4436 100644 --- a/problems/知识星球精选/关于实习大家的疑问.md +++ b/problems/知识星球精选/关于实习大家的疑问.md @@ -1,11 +1,11 @@

- + # 关于实习,大家可能有点迷茫! -我在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里回答了很多关于实习相关的问题,其实很多录友可能都有这么样的疑问,主要关于实习的问题有如下四点: +我在[知识星球](https://programmercarl.com/other/kstar.html)里回答了很多关于实习相关的问题,其实很多录友可能都有这么样的疑问,主要关于实习的问题有如下四点: * 秋招什么时候开始准备 * 要不要准备实习 diff --git a/problems/知识星球精选/关于提前批的一些建议.md b/problems/知识星球精选/关于提前批的一些建议.md index 415a8b2f..6a316bd2 100644 --- a/problems/知识星球精选/关于提前批的一些建议.md +++ b/problems/知识星球精选/关于提前批的一些建议.md @@ -1,5 +1,5 @@

- + @@ -9,7 +9,7 @@ 以前提前批,都是 8月份,8月份中序左右,而不少大厂现在就已经提前批了。 -不少录友在 公众号留言,和[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,表示提前批来的还是有点快。 +不少录友在 公众号留言,和[知识星球](https://programmercarl.com/other/kstar.html)里,表示提前批来的还是有点快。 ![](https://code-thinking-1253855093.cos.ap-guangzhou.myqcloud.com/pics/20210618162214.png) diff --git a/problems/知识星球精选/写简历的一些问题.md b/problems/知识星球精选/写简历的一些问题.md index af42cea1..426eb2a6 100644 --- a/problems/知识星球精选/写简历的一些问题.md +++ b/problems/知识星球精选/写简历的一些问题.md @@ -1,11 +1,11 @@

- + # 程序员应该这么写简历! -自运营[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)以来,我已经给星球里的录友们看了 一百多份简历,并准对大家简历上的问题都给出了对应的详细建议。 +自运营[知识星球](https://programmercarl.com/other/kstar.html)以来,我已经给星球里的录友们看了 一百多份简历,并准对大家简历上的问题都给出了对应的详细建议。 社招,校招,实习的都有,其实大家的简历看多了,发现有很多共性的问题,这里就和大家分享一下。 diff --git a/problems/知识星球精选/初入大三选择考研VS工作.md b/problems/知识星球精选/初入大三选择考研VS工作.md index ba675761..f602e9e9 100644 --- a/problems/知识星球精选/初入大三选择考研VS工作.md +++ b/problems/知识星球精选/初入大三选择考研VS工作.md @@ -1,6 +1,6 @@

- + @@ -8,7 +8,7 @@ 9月份开学季,已过,一些录友也升入大三了,升入大三摆在自己面前最大的问题就是,考研还是找工作? -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里就有录友问我这样一个问题, 其实每个人情况不一样,做出的选择也不一样,这里给大家分享一下,相信对你也会有启发。 +在[知识星球](https://programmercarl.com/other/kstar.html)里就有录友问我这样一个问题, 其实每个人情况不一样,做出的选择也不一样,这里给大家分享一下,相信对你也会有启发。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211002110618.png) diff --git a/problems/知识星球精选/刷力扣用不用库函数.md b/problems/知识星球精选/刷力扣用不用库函数.md index 73f2a2d5..b52e4d03 100644 --- a/problems/知识星球精选/刷力扣用不用库函数.md +++ b/problems/知识星球精选/刷力扣用不用库函数.md @@ -1,11 +1,11 @@

- + # 究竟什么时候用库函数,什么时候要自己实现 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里有录友问我,刷题究竟要不要用库函数? 刷题的时候总是禁不住库函数的诱惑,如果都不用库函数一些题目做起来还很麻烦。 +在[知识星球](https://programmercarl.com/other/kstar.html)里有录友问我,刷题究竟要不要用库函数? 刷题的时候总是禁不住库函数的诱惑,如果都不用库函数一些题目做起来还很麻烦。 估计不少录友都有这个困惑,我来说一说对于库函数的使用。 diff --git a/problems/知识星球精选/刷题攻略要刷两遍.md b/problems/知识星球精选/刷题攻略要刷两遍.md index 1f4fd7f9..285a5728 100644 --- a/problems/知识星球精选/刷题攻略要刷两遍.md +++ b/problems/知识星球精选/刷题攻略要刷两遍.md @@ -1,5 +1,5 @@

- + @@ -27,7 +27,7 @@ 第三遍基本就得心应手了。 -在[「代码随想录」知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)中,我都是强调大家要至少刷两遍,有时间的话刷三遍, +在[「代码随想录」知识星球](https://programmercarl.com/other/kstar.html)中,我都是强调大家要至少刷两遍,有时间的话刷三遍, 可以看看星球里录友们的打卡: diff --git a/problems/知识星球精选/博士转行计算机.md b/problems/知识星球精选/博士转行计算机.md index 66769264..4da79e97 100644 --- a/problems/知识星球精选/博士转行计算机.md +++ b/problems/知识星球精选/博士转行计算机.md @@ -1,11 +1,11 @@

- + # 本硕非计算机博士,如果找计算机相关工作 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,有一位博士录友,本硕都不是计算机,博士转的计算机,问了这样一个问题 +在[知识星球](https://programmercarl.com/other/kstar.html)里,有一位博士录友,本硕都不是计算机,博士转的计算机,问了这样一个问题 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210903213924.png) diff --git a/problems/知识星球精选/合适自己的就是最好的.md b/problems/知识星球精选/合适自己的就是最好的.md index fda51afa..dc31f5a7 100644 --- a/problems/知识星球精选/合适自己的就是最好的.md +++ b/problems/知识星球精选/合适自己的就是最好的.md @@ -1,5 +1,5 @@

- + @@ -7,7 +7,7 @@ 秋招已经进入下半场了,不少同学也拿到了offer,但不是说非要进大厂,每个人情况都不一样,**合适自己的,就是最好的!**。 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里有一位录友,就终于拿到了合适自己的offer,并不是大厂,是南京的一家公司,**但很合适自己,其实就非常值得开心**。 +[知识星球](https://programmercarl.com/other/kstar.html)里有一位录友,就终于拿到了合适自己的offer,并不是大厂,是南京的一家公司,**但很合适自己,其实就非常值得开心**。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210910232502.png) @@ -33,5 +33,5 @@ 我在发文的时候 看了一遍她这几个月完整的打卡过程,还是深有感触的。 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里还有很多很多这样的录友在每日奋斗着,**我相信 等大家拿到offer之后,在回头看一下当初星球里曾经每日打卡的点点滴滴,不仅会感动自己 也会感动每一位见证者**。 +[知识星球](https://programmercarl.com/other/kstar.html)里还有很多很多这样的录友在每日奋斗着,**我相信 等大家拿到offer之后,在回头看一下当初星球里曾经每日打卡的点点滴滴,不仅会感动自己 也会感动每一位见证者**。 diff --git a/problems/知识星球精选/备战2022届秋招.md b/problems/知识星球精选/备战2022届秋招.md index 207a5e2a..55c2a3bf 100644 --- a/problems/知识星球精选/备战2022届秋招.md +++ b/problems/知识星球精选/备战2022届秋招.md @@ -1,11 +1,11 @@

- + # 要开始准备2022届的秋招了 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里准备秋招的录友还真不少,也会回答过不少关于秋招的问题。 +在[知识星球](https://programmercarl.com/other/kstar.html)里准备秋招的录友还真不少,也会回答过不少关于秋招的问题。 ![](https://img-blog.csdnimg.cn/20210507195443924.png) diff --git a/problems/知识星球精选/大厂新人培养体系.md b/problems/知识星球精选/大厂新人培养体系.md index ccd2f1c2..0e905e42 100644 --- a/problems/知识星球精选/大厂新人培养体系.md +++ b/problems/知识星球精选/大厂新人培养体系.md @@ -1,11 +1,11 @@

- + # 大厂的新人培养体系是什么样的 -之前我一直在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)和大家讲,能进大厂一定要进大厂,大厂有比较好的培养体系。 +之前我一直在[知识星球](https://programmercarl.com/other/kstar.html)和大家讲,能进大厂一定要进大厂,大厂有比较好的培养体系。 也有录友在星球里问我,究竟培养体系应该是什么样的呢? 大厂都会这么培养新人么? diff --git a/problems/知识星球精选/天下乌鸦一般黑.md b/problems/知识星球精选/天下乌鸦一般黑.md index 29543747..ccd1c326 100644 --- a/problems/知识星球精选/天下乌鸦一般黑.md +++ b/problems/知识星球精选/天下乌鸦一般黑.md @@ -1,6 +1,6 @@

- + @@ -8,7 +8,7 @@ 相信大家应该经常在 各大论坛啊之类的 看到对各个互联网公司的评价,有风评好的,也有风评不好的。 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里有录友问我这样一个问题: +在[知识星球](https://programmercarl.com/other/kstar.html)里有录友问我这样一个问题: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211004095707.png) diff --git a/problems/知识星球精选/如何权衡实习与秋招复习.md b/problems/知识星球精选/如何权衡实习与秋招复习.md index 275588df..07e2bba6 100644 --- a/problems/知识星球精选/如何权衡实习与秋招复习.md +++ b/problems/知识星球精选/如何权衡实习与秋招复习.md @@ -1,11 +1,11 @@

- + # 已经在实习的录友如何准备秋招? -最近在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)一位录友问了实习生如何权衡工作和准备秋招的问题。 +最近在[知识星球](https://programmercarl.com/other/kstar.html)一位录友问了实习生如何权衡工作和准备秋招的问题。 ![](https://code-thinking-1253855093.cos.ap-guangzhou.myqcloud.com/pics/20210703230618.png) diff --git a/problems/知识星球精选/客三消.md b/problems/知识星球精选/客三消.md index 8a7b5fc6..6b81ab2c 100644 --- a/problems/知识星球精选/客三消.md +++ b/problems/知识星球精选/客三消.md @@ -1,5 +1,5 @@

- + @@ -17,7 +17,7 @@ 然后朋友圈就炸了,上百条的留言,问我这是为啥。 -其实这个问题在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里也有录友问过我。 +其实这个问题在[知识星球](https://programmercarl.com/other/kstar.html)里也有录友问过我。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210905091037.png) @@ -87,7 +87,7 @@ # 总结 -以上就是我在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里的详细回答。 +以上就是我在[知识星球](https://programmercarl.com/other/kstar.html)里的详细回答。 注意我这里说的一般情况,当然各个岗位都有佼佼者,或者说大牛,客户端也有大牛,也很香,不过这是极少数,就不在讨论范围内了。 diff --git a/problems/知识星球精选/技术不好如何选择技术方向.md b/problems/知识星球精选/技术不好如何选择技术方向.md index dd13f46b..4ad4659b 100644 --- a/problems/知识星球精选/技术不好如何选择技术方向.md +++ b/problems/知识星球精选/技术不好如何选择技术方向.md @@ -1,11 +1,11 @@

- + # 技术不太好,也不知道对技术有没有兴趣,我该怎么选? -最近在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里解答了不少录友们的疑惑,其实发现一个挺普遍的问题: +最近在[知识星球](https://programmercarl.com/other/kstar.html)里解答了不少录友们的疑惑,其实发现一个挺普遍的问题: * 我技术很一般 * 对技术也没有什么追求 diff --git a/problems/知识星球精选/提前批已经开始了.md b/problems/知识星球精选/提前批已经开始了.md index ba05b5a9..3e255746 100644 --- a/problems/知识星球精选/提前批已经开始了.md +++ b/problems/知识星球精选/提前批已经开始了.md @@ -1,5 +1,5 @@

- + @@ -7,7 +7,7 @@ 最近华为提前批已经开始了,不少同学已经陆续参加了提前批的面试。 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)上就有录友问我这么个问题: +在[知识星球](https://programmercarl.com/other/kstar.html)上就有录友问我这么个问题: ![](https://code-thinking-1253855093.cos.ap-guangzhou.myqcloud.com/pics/20210711002802.png) diff --git a/problems/知识星球精选/秋招下半场依然没offer.md b/problems/知识星球精选/秋招下半场依然没offer.md index 829f82ba..5862dd32 100644 --- a/problems/知识星球精选/秋招下半场依然没offer.md +++ b/problems/知识星球精选/秋招下半场依然没offer.md @@ -1,11 +1,11 @@

- + # 秋招下半场依然没offer,怎么办? -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里一些录友拿到了满意的offer,也有一些录友,依然没有offer,每天的状态已经不能用焦虑来形容了。 +[知识星球](https://programmercarl.com/other/kstar.html)里一些录友拿到了满意的offer,也有一些录友,依然没有offer,每天的状态已经不能用焦虑来形容了。 在星球里就有录友向我提问了这样一个问题: @@ -52,7 +52,7 @@ ## 在学点技术,冲春招? -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里还有一位录友,也是类似的情况,秋招感觉很艰难,要不要在学一学微服务分布式之类的,再冲春招。 +[知识星球](https://programmercarl.com/other/kstar.html)里还有一位录友,也是类似的情况,秋招感觉很艰难,要不要在学一学微服务分布式之类的,再冲春招。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210921103343.png) @@ -71,13 +71,13 @@ ## 给参加明年秋招录友的劝告 -其实我在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,**看到了太多太多 参加今年秋招的录友 埋怨自己 准备的太晚了,没想到要看的东西这么多,没想到竞争这么激烈**。 +其实我在[知识星球](https://programmercarl.com/other/kstar.html)里,**看到了太多太多 参加今年秋招的录友 埋怨自己 准备的太晚了,没想到要看的东西这么多,没想到竞争这么激烈**。 所以明年参加秋招的录友,要提前就开始准备,明确自己的岗位,知道岗位的要求,制定自己的计划,然后按计划执行。 **其实多早开始准备,都不算早!** -很多在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里的准大三,研一的录友,都能在星球里感受到 秋招的竞争与激烈。 +很多在[知识星球](https://programmercarl.com/other/kstar.html)里的准大三,研一的录友,都能在星球里感受到 秋招的竞争与激烈。 所以他们也就早早的开始准备了。 @@ -87,7 +87,7 @@ 估计大多数准大三或者准研一的同学都还没有这种意识。 -**但在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,通过每天录友们的打卡,每天都能感受到这种紧迫感**。 +**但在[知识星球](https://programmercarl.com/other/kstar.html)里,通过每天录友们的打卡,每天都能感受到这种紧迫感**。 正如一位星球里的录友这么说: diff --git a/problems/知识星球精选/秋招开奖.md b/problems/知识星球精选/秋招开奖.md index 368596b6..82686785 100644 --- a/problems/知识星球精选/秋招开奖.md +++ b/problems/知识星球精选/秋招开奖.md @@ -1,6 +1,6 @@

- + @@ -8,7 +8,7 @@ 最近秋招的录友已经陆续开奖了,同时开奖多少,也是offer选择的一个重要因素,毕竟谁能和钱过意不去呢。 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里这位录友拿到的百度offer薪资确实很高 +[知识星球](https://programmercarl.com/other/kstar.html)里这位录友拿到的百度offer薪资确实很高 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211023102430.png) diff --git a/problems/知识星球精选/秋招总结1.md b/problems/知识星球精选/秋招总结1.md index efec67ee..2aec24dc 100644 --- a/problems/知识星球精选/秋招总结1.md +++ b/problems/知识星球精选/秋招总结1.md @@ -1,5 +1,5 @@

- + @@ -11,7 +11,7 @@ 时间总是过得很快,但曾经焦虑的小伙,现在也拿到几个offer了,不一定人人都要冲大厂,卷算法,卷后端,合适自己就好,要不然会把自己搞的很累。 -以下是他的秋招总结,**写的很用心,说了很多面试中使用的方法,发在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里,立刻就引来星球小伙伴们的围观**,算是给星球里明年要秋招的录友做了一个参考。 +以下是他的秋招总结,**写的很用心,说了很多面试中使用的方法,发在[知识星球](https://programmercarl.com/other/kstar.html)里,立刻就引来星球小伙伴们的围观**,算是给星球里明年要秋招的录友做了一个参考。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211109231150.png) diff --git a/problems/知识星球精选/秋招总结2.md b/problems/知识星球精选/秋招总结2.md index 7f4b6770..897a7ec3 100644 --- a/problems/知识星球精选/秋招总结2.md +++ b/problems/知识星球精选/秋招总结2.md @@ -1,10 +1,10 @@ -

+

# 倒霉透顶,触底反弹! -星球里不少录友秋招已经陆续结束了,很多录友都在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里写下了自己的秋招总结,但今天这位录友很特殊,甚至我给她修改简历的时候我都“有点愁”。 +星球里不少录友秋招已经陆续结束了,很多录友都在[知识星球](https://programmercarl.com/other/kstar.html)里写下了自己的秋招总结,但今天这位录友很特殊,甚至我给她修改简历的时候我都“有点愁”。 他的秋招过程也是极其坎坷,**逼签、被养鱼最后收到感谢信、校招流程收到实习offer,还有数不清的简历挂……**,可能是太倒霉了,最后触底反弹,接到了百度的offer,虽然是白菜价,但真的很不错了。 diff --git a/problems/知识星球精选/秋招总结3.md b/problems/知识星球精选/秋招总结3.md index 895c1b8c..05a677ed 100644 --- a/problems/知识星球精选/秋招总结3.md +++ b/problems/知识星球精选/秋招总结3.md @@ -1,4 +1,4 @@ -

+

@@ -6,7 +6,7 @@ 其实无论社招,还是校招,心态都很重要,例如,别人那个一堆offer,自己陷入深深的焦虑。 面试分明感觉自己表现的不错,结果就是挂了。面试中遇到了面试官的否定,然后就开始自我怀疑,等等等。 -如果你也遇到这些问题,可以认真读完[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里一位录友的总结,他是非科班,机械转码,今年5月份加入的星球,坚持打卡几个月,如果也获得自己心仪的offer,他的心路历程对大家会很有启发。 +如果你也遇到这些问题,可以认真读完[知识星球](https://programmercarl.com/other/kstar.html)里一位录友的总结,他是非科班,机械转码,今年5月份加入的星球,坚持打卡几个月,如果也获得自己心仪的offer,他的心路历程对大家会很有启发。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211121093438.png) diff --git a/problems/知识星球精选/秋招的上半场.md b/problems/知识星球精选/秋招的上半场.md index f404e611..6c817577 100644 --- a/problems/知识星球精选/秋招的上半场.md +++ b/problems/知识星球精选/秋招的上半场.md @@ -1,11 +1,11 @@

- + # 秋招上半场的总结 -八月份已经接近尾声,不少录友已经在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 已经总结了秋招的上半场。 +八月份已经接近尾声,不少录友已经在[知识星球](https://programmercarl.com/other/kstar.html) 已经总结了秋招的上半场。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210829214839.png) diff --git a/problems/知识星球精选/秋招进行中的迷茫与焦虑.md b/problems/知识星球精选/秋招进行中的迷茫与焦虑.md index 6083c7b1..24e7760c 100644 --- a/problems/知识星球精选/秋招进行中的迷茫与焦虑.md +++ b/problems/知识星球精选/秋招进行中的迷茫与焦虑.md @@ -1,5 +1,5 @@

- + @@ -9,7 +9,7 @@ 特别是大三的同学吧,同时面临这找工作和考研两个方向的诱惑。 -一位录友就在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)问了我这个问题: +一位录友就在[知识星球](https://programmercarl.com/other/kstar.html)问了我这个问题: ![](https://code-thinking-1253855093.cos.ap-guangzhou.myqcloud.com/pics/20210724183240.png) diff --git a/problems/知识星球精选/英语到底重不重要.md b/problems/知识星球精选/英语到底重不重要.md index 32e6a39b..5ee7fc2d 100644 --- a/problems/知识星球精选/英语到底重不重要.md +++ b/problems/知识星球精选/英语到底重不重要.md @@ -1,11 +1,11 @@

- + # 对程序员来说,英语到底重不重要 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)有一位录友问了我这么一个问题。 +在[知识星球](https://programmercarl.com/other/kstar.html)有一位录友问了我这么一个问题。 ![](https://gitee.com/programmercarl/pics/raw/master/pic1/20210605193955.png) diff --git a/problems/知识星球精选/要不要考研.md b/problems/知识星球精选/要不要考研.md index a5f2dfa0..180e5d13 100644 --- a/problems/知识星球精选/要不要考研.md +++ b/problems/知识星球精选/要不要考研.md @@ -1,11 +1,11 @@

- + # 到底要不要读研 -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里讨论了一下关于要不要读研的问题。 +在[知识星球](https://programmercarl.com/other/kstar.html)里讨论了一下关于要不要读研的问题。 ![](https://gitee.com/programmercarl/pics/raw/master/pic1/20210613230829.png) diff --git a/problems/知识星球精选/逼签.md b/problems/知识星球精选/逼签.md index 90e4e67d..f75e3642 100644 --- a/problems/知识星球精选/逼签.md +++ b/problems/知识星球精选/逼签.md @@ -7,7 +7,7 @@ 如果是心仪的公司要求三天内签三方,我相信大家就没有被逼签的感觉了,哈哈哈 -[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)里很多录友都问我,XX公司又要逼签了,怎么办。 我在公众号也分享一下,希望对大家有所帮助。 +[知识星球](https://programmercarl.com/other/kstar.html)里很多录友都问我,XX公司又要逼签了,怎么办。 我在公众号也分享一下,希望对大家有所帮助。 ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211017093816.png) diff --git a/problems/知识星球精选/非科班2021秋招总结.md b/problems/知识星球精选/非科班2021秋招总结.md index c2c7ed33..b92420ad 100644 --- a/problems/知识星球精选/非科班2021秋招总结.md +++ b/problems/知识星球精选/非科班2021秋招总结.md @@ -1,6 +1,6 @@

- + @@ -10,7 +10,7 @@ 其中一位录友写的很好,所以想分享出来 给公众号上的录友也看一看,相信对大家有所启发,特别是明年要找工作的录友,值得好好看一看。 -这篇总结首发在代码随想录[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)上,立刻就获得了60个赞,很多评论,我这里放出一个截图: +这篇总结首发在代码随想录[知识星球](https://programmercarl.com/other/kstar.html)上,立刻就获得了60个赞,很多评论,我这里放出一个截图: ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210929220903.png) diff --git a/problems/知识星球精选/非科班的困扰.md b/problems/知识星球精选/非科班的困扰.md index d5fea532..470b233b 100644 --- a/problems/知识星球精选/非科班的困扰.md +++ b/problems/知识星球精选/非科班的困扰.md @@ -1,11 +1,11 @@

- + # 非科班的困扰! -在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) 里很多录友都是非科班转码的,也是要准备求职,或者准备明年秋招,非科班的录友其实对 准备找工作所需要的知识不太清楚,对其难度也不太清楚,所有总感觉准备起来心里没有底。 +在[知识星球](https://programmercarl.com/other/kstar.html) 里很多录友都是非科班转码的,也是要准备求职,或者准备明年秋招,非科班的录友其实对 准备找工作所需要的知识不太清楚,对其难度也不太清楚,所有总感觉准备起来心里没有底。 例如星球里有这位录友的提问: diff --git a/problems/知识星球精选/面试中发散性问题.md b/problems/知识星球精选/面试中发散性问题.md index 7fb9150f..5cade944 100644 --- a/problems/知识星球精选/面试中发散性问题.md +++ b/problems/知识星球精选/面试中发散性问题.md @@ -1,11 +1,11 @@

- + # 面试中遇到发散性问题,应该怎么办? -这周在[知识星球](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)有一位录友问了我这么一个问题,我感觉挺有代表性的,应该不少录友在面试中不论是社招还是校招都会遇到这一类的问题。 +这周在[知识星球](https://programmercarl.com/other/kstar.html)有一位录友问了我这么一个问题,我感觉挺有代表性的,应该不少录友在面试中不论是社招还是校招都会遇到这一类的问题。 问题如下: From 759175ac6fc72b63e3c4aa02e7b893951556146d Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Tue, 22 Mar 2022 09:30:23 +0800 Subject: [PATCH 215/257] Update --- .DS_Store | Bin 8196 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 7794435bd6714aed6095604325ab6ffe84221748..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMU2GIp6u#fIv@>*|1GG|b$8K6szzU`1r~D<`KM+bOc3ZkFVA<^sbYMDDcV^o{ zC8_Z*g7~0DeNjN;ix1VP7!wtvi3asattOIaj7FnRKFACD;<m0CQ8r?%*`* zup!Jqn1L_@VFtnsgc#mK>qC@oE@Ocl6VhKgsPK;f zB>54*zv!9H0lrT(kg-6H3F*61pW^g@z!kv}1Hzs3QEpB$7RWIng*$_AX9z|{a6*AU zI{8I?bB36ZVHsv1%)s;vaQet>kY$*|QrDl~QTewYB!ubsmP_3Yqqra9{olWg+mlT+n{GUw!6>BxFmbE zVwVEl+2`1MGX~dp^*L5{z;=7J1${}YFKZ<|qu#RO<_Uw^irv19V_AD0*W}%FCp=@s z+c#eT{C4F9d>fSP!^y{nJ6w>vh?lONbu4&8|RHg%m zmHORkhfBfBT2dIUR;$&HV*~|7b45$7x?bVg$!AiU;v1PT@4p;3+(h7x5C#;XGc$n|KQs@D4u2 zC47d@@il(J&-ewu;tyQKU-(*}`EPl8aOHV4$};qPPqUrg~a?_**LUMB<#)$$zerqZ#K$YPAhoU&S> zu&z*-$r>?ej;P+Hu9USFMJo{1s>o{MrL0MQRb3mYRkWn6<%w!lWTPT$5S7j9R?b5$ zUsQE9rYIWoE0M-XGv|^f6Uxsu`LjI>%9Uv=l#lj1Ssi`Gb+E&<$vniKWM>KOAFzw; zOLm$4$bMs22=4`ibPeTLfog0(4BN2-yU>DG>_Zp2(L-oAaM(xuF?h&gm{5NL591L$ zhR5*)p2jnH7SG`$w)*YO6S|2@2qi-i7<@G-u?1it6^4^W#!bE~N5N?f6* zX=ombXKc%{kB~0smvguYWuAEFGJgJVp8fa#n=rEQmBS2#8ThXmKz>uase!C#ThsVi zJ4*K From 77aa72b984465ac28006cc9c5765ecb42681811e Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Wed, 23 Mar 2022 16:13:01 +0800 Subject: [PATCH 216/257] Update --- README.md | 2 +- problems/0028.实现strStr.md | 2 +- problems/0494.目标和.md | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0bf7fcdf..b8ff87da 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ 3. [二叉树:听说递归能做的,栈也能做!](./problems/二叉树的迭代遍历.md) 4. [二叉树:前中后序迭代方式的写法就不能统一一下么?](./problems/二叉树的统一迭代法.md) 5. [二叉树:层序遍历登场!](./problems/0102.二叉树的层序遍历.md) -6. [二叉树:你真的会翻转二叉树么?](./problems/0226.翻转二叉树.md) +6. [二叉树:你真的会翻转二叉树么?](./problems/0226.翻转二叉树.md) 7. [本周小结!(二叉树)](./problems/周总结/20200927二叉树周末总结.md) 8. [二叉树:我对称么?](./problems/0101.对称二叉树.md) 9. [二叉树:看看这些树的最大深度](./problems/0104.二叉树的最大深度.md) diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index bbe5b80f..854789ee 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -255,7 +255,7 @@ void getNext(int* next, const string& s) 1. 初始化: -定义两个指针i和j,j指向前缀起始位置,i指向后缀起始位置。 +定义两个指针i和j,j指向前缀末尾位置,i指向后缀末尾位置。 然后还要对next数组进行初始化赋值,如下: diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 47d0784e..df667a85 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -156,11 +156,10 @@ dp[j] 表示:填满j(包括j)这么大容积的包,有dp[j]种方法 有哪些来源可以推出dp[j]呢? -填满容量为j - nums[i]的背包,有dp[j - nums[i]]种方法。 +不考虑nums[i]的情况下,填满容量为j - nums[i]的背包,有dp[j - nums[i]]种方法。 那么只要搞到nums[i]的话,凑成dp[j]就有dp[j - nums[i]] 种方法。 - 例如:dp[j],j 为5, * 已经有一个1(nums[i]) 的话,有 dp[4]种方法 凑成 dp[5]。 From cbe5403e45e009f5d906fa168ff5aee086043e57 Mon Sep 17 00:00:00 2001 From: berserk-112 <40333359+berserk-112@users.noreply.github.com> Date: Thu, 24 Mar 2022 11:23:36 +0800 Subject: [PATCH 217/257] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bf7fcdf..5dfc04fd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ - +贪心:[贪心算法:分发糖果](./problems/0135.分发糖果.md) [贪心算法:根据身高重建队列](./problems/0406.根据身高重建队列.md) 👉 推荐 [在线阅读](http://programmercarl.com/) (Github在国内访问经常不稳定) 👉 推荐 [Gitee同步](https://gitee.com/programmercarl/leetcode-master) From 5c403d9e589203d8ee7c2beff3c863accb3bce94 Mon Sep 17 00:00:00 2001 From: berserk-112 <40333359+berserk-112@users.noreply.github.com> Date: Fri, 25 Mar 2022 11:08:45 +0800 Subject: [PATCH 218/257] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5dfc04fd..a0f4863e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -贪心:[贪心算法:分发糖果](./problems/0135.分发糖果.md) [贪心算法:根据身高重建队列](./problems/0406.根据身高重建队列.md) +贪心:[贪心算法:分发糖果](./problems/0135.分发糖果.md) [贪心算法:根据身高重建队列](./problems/0406.根据身高重建队列.md) [贪心算法:我要监控二叉树!](./problems/0968.监控二叉树.md) 👉 推荐 [在线阅读](http://programmercarl.com/) (Github在国内访问经常不稳定) 👉 推荐 [Gitee同步](https://gitee.com/programmercarl/leetcode-master) From 74ac8c39c1248afd5d99604b7a20e27c67625679 Mon Sep 17 00:00:00 2001 From: Guang-Hou <87743934+Guang-Hou@users.noreply.github.com> Date: Fri, 25 Mar 2022 15:49:48 -0400 Subject: [PATCH 219/257] =?UTF-8?q?Update=200134.=E5=8A=A0=E6=B2=B9?= =?UTF-8?q?=E7=AB=99.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0134.加油站.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index ca95af67..f73ab9f4 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -239,6 +239,30 @@ class Solution { ### Python ```python +# 解法1 +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + n = len(gas) + cur_sum = 0 + min_sum = float('inf') + + for i in range(n): + cur_sum += gas[i] - cost[i] + min_sum = min(min_sum, cur_sum) + + if cur_sum < 0: return -1 + if min_sum >= 0: return 0 + + for j in range(n - 1, 0, -1): + min_sum += gas[j] - cost[j] + if min_sum >= 0: + return j + + return -1 +``` + +```python +# 解法2 class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: start = 0 From dd8bea8335794b48969ae89572aec8c7aec35231 Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Fri, 25 Mar 2022 20:23:39 -0500 Subject: [PATCH 220/257] =?UTF-8?q?0112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C=20python=20=E7=B2=BE=E7=AE=80=E9=80=92=E5=BD=92?= =?UTF-8?q?=E5=9B=9E=E6=BA=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0112.路径总和 python 为113精简递归回溯 --- problems/0112.路径总和.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5db36687..03ec1bb7 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -504,17 +504,13 @@ class solution: if cur_node.left: path.append(cur_node.left.val) - remain -= cur_node.left.val - traversal(cur_node.left, remain) + traversal(cur_node.left, remain-cur_node.left.val) path.pop() - remain += cur_node.left.val if cur_node.right: path.append(cur_node.right.val) - remain -= cur_node.right.val - traversal(cur_node.right, remain) + traversal(cur_node.right, remain-cur_node.left.val) path.pop() - remain += cur_node.right.val result, path = [], [] if not root: From f8392906ac8463504e2707f3762e3fc39f909782 Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Fri, 25 Mar 2022 20:25:06 -0500 Subject: [PATCH 221/257] =?UTF-8?q?0112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C=20python=20=E7=B2=BE=E7=AE=80=E9=80=92=E5=BD=92?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E6=9D=A1=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0112.路径总和 python 精简113递归返回条件 --- problems/0112.路径总和.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 03ec1bb7..ff682739 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -496,11 +496,10 @@ class solution: def pathsum(self, root: treenode, targetsum: int) -> list[list[int]]: def traversal(cur_node, remain): - if not cur_node.left and not cur_node.right and remain == 0: - result.append(path[:]) - return - - if not cur_node.left and not cur_node.right: return + if not cur_node.left and not cur_node.right: + if remain == 0: + result.append(path[:]) + return if cur_node.left: path.append(cur_node.left.val) From be6cb9f13086cd8ea7a82a98226b02666f10cdb3 Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Fri, 25 Mar 2022 20:35:54 -0500 Subject: [PATCH 222/257] =?UTF-8?q?0112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C=20python=20113=E6=B7=BB=E5=8A=A0=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0112.路径总和 python 113添加迭代法 --- problems/0112.路径总和.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index ff682739..1904e92b 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -519,6 +519,30 @@ class solution: return result ``` +**迭代法,用第二个队列保存目前的总和与路径** +```python +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + if not root: + return [] + que, temp = deque([root]), deque([(root.val, [root.val])]) + result = [] + while que: + for _ in range(len(que)): + node = que.popleft() + value, path = temp.popleft() + if (not node.left) and (not node.right): + if value == targetSum: + result.append(path) + if node.left: + que.append(node.left) + temp.append((node.left.val+value, path+[node.left.val])) + if node.right: + que.append(node.right) + temp.append((node.right.val+value, path+[node.right.val])) + return result +``` + ## go 112. 路径总和 From 9dbc51455d7f13b83fe63d30a477d89fd1e0c33a Mon Sep 17 00:00:00 2001 From: xuerbujia <83055661+xuerbujia@users.noreply.github.com> Date: Sat, 26 Mar 2022 10:03:04 +0800 Subject: [PATCH 223/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880141.?= =?UTF-8?q?=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0141.环形链表.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/problems/0141.环形链表.md b/problems/0141.环形链表.md index 0712a2a2..ddd83c94 100644 --- a/problems/0141.环形链表.md +++ b/problems/0141.环形链表.md @@ -106,6 +106,21 @@ class Solution: ## Go ```go +func hasCycle(head *ListNode) bool { + if head==nil{ + return false + } //空链表一定不会有环 + fast:=head + slow:=head //快慢指针 + for fast.Next!=nil&&fast.Next.Next!=nil{ + fast=fast.Next.Next + slow=slow.Next + if fast==slow{ + return true //快慢指针相遇则有环 + } + } + return false +} ``` ### JavaScript From 1fa83c2b3f6b1eded21f2f5313be38b1a72ff2e5 Mon Sep 17 00:00:00 2001 From: xuerbujia <83055661+xuerbujia@users.noreply.github.com> Date: Sat, 26 Mar 2022 10:13:44 +0800 Subject: [PATCH 224/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880189.?= =?UTF-8?q?=E8=BD=AE=E8=BD=AC=E6=95=B0=E7=BB=84.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0189.旋转数组.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/problems/0189.旋转数组.md b/problems/0189.旋转数组.md index bbe152a2..8e39d253 100644 --- a/problems/0189.旋转数组.md +++ b/problems/0189.旋转数组.md @@ -124,6 +124,19 @@ class Solution: ## Go ```go +func rotate(nums []int, k int) { + l:=len(nums) + index:=l-k%l + reverse(nums) + reverse(nums[:l-index]) + reverse(nums[l-index:]) +} +func reverse(nums []int){ + l:=len(nums) + for i:=0;i Date: Sat, 26 Mar 2022 21:47:35 -0500 Subject: [PATCH 225/257] =?UTF-8?q?=E5=A2=9E=E5=8A=A0python=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/0127.单词接龙.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 407596c0..584bcb2a 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -134,7 +134,29 @@ public int ladderLength(String beginWord, String endWord, List wordList) ``` ## Python - +``` +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + wordSet = set(wordList) + if len(wordSet)== 0 or endWord not in wordSet: + return 0 + mapping = {beginWord:1} + queue = deque([beginWord]) + while queue: + word = queue.popleft() + path = mapping[word] + for i in range(len(word)): + word_list = list(word) + for j in range(26): + word_list[i] = chr(ord('a')+j) + newWord = "".join(word_list) + if newWord == endWord: + return path+1 + if newWord in wordSet and newWord not in mapping: + mapping[newWord] = path+1 + queue.append(newWord) + return 0 +``` ## Go ## JavaScript From 6d1746db85853e3714b194c659335a71a69d2d0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Mon, 28 Mar 2022 09:55:29 +0800 Subject: [PATCH 226/257] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index a0f4863e..78813ac3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -贪心:[贪心算法:分发糖果](./problems/0135.分发糖果.md) [贪心算法:根据身高重建队列](./problems/0406.根据身高重建队列.md) [贪心算法:我要监控二叉树!](./problems/0968.监控二叉树.md) 👉 推荐 [在线阅读](http://programmercarl.com/) (Github在国内访问经常不稳定) 👉 推荐 [Gitee同步](https://gitee.com/programmercarl/leetcode-master) From 0296ac0a0e4e0b7f0b63ded21004ccf24f755a60 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 28 Mar 2022 14:33:49 +0800 Subject: [PATCH 227/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880017.?= =?UTF-8?q?=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81=E7=9A=84=E5=AD=97=E6=AF=8D?= =?UTF-8?q?=E7=BB=84=E5=90=88.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesr?= =?UTF-8?q?ipt=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0017.电话号码的字母组合.md | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 7040182f..94136565 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -420,6 +420,40 @@ var letterCombinations = function(digits) { }; ``` +## TypeScript + +```typescript +function letterCombinations(digits: string): string[] { + if (digits === '') return []; + const strMap: { [index: string]: string[] } = { + 1: [], + 2: ['a', 'b', 'c'], + 3: ['d', 'e', 'f'], + 4: ['g', 'h', 'i'], + 5: ['j', 'k', 'l'], + 6: ['m', 'n', 'o'], + 7: ['p', 'q', 'r', 's'], + 8: ['t', 'u', 'v'], + 9: ['w', 'x', 'y', 'z'], + } + const resArr: string[] = []; + function backTracking(digits: string, curIndex: number, route: string[]): void { + if (curIndex === digits.length) { + resArr.push(route.join('')); + return; + } + let tempArr: string[] = strMap[digits[curIndex]]; + for (let i = 0, length = tempArr.length; i < length; i++) { + route.push(tempArr[i]); + backTracking(digits, curIndex + 1, route); + route.pop(); + } + } + backTracking(digits, 0, []); + return resArr; +}; +``` + ## C ```c From 4959bd4c8aa78d401f5a1f14c2d267a4d046baf5 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 28 Mar 2022 17:15:46 +0800 Subject: [PATCH 228/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880039.?= =?UTF-8?q?=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8C.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0039.组合总和.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index 7a2084dd..98b37b84 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -392,7 +392,34 @@ var combinationSum = function(candidates, target) { }; ``` +## TypeScript + +```typescript +function combinationSum(candidates: number[], target: number): number[][] { + const resArr: number[][] = []; + function backTracking( + candidates: number[], target: number, + startIndex: number, route: number[], curSum: number + ): void { + if (curSum > target) return; + if (curSum === target) { + resArr.push(route.slice()); + return + } + for (let i = startIndex, length = candidates.length; i < length; i++) { + let tempVal: number = candidates[i]; + route.push(tempVal); + backTracking(candidates, target, i, route, curSum + tempVal); + route.pop(); + } + } + backTracking(candidates, target, 0, [], 0); + return resArr; +}; +``` + ## C + ```c int* path; int pathTop; From a021470215aa859a4d5b0e9fe48dd775e6c0ed51 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Tue, 29 Mar 2022 14:38:19 +0800 Subject: [PATCH 229/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880040.?= =?UTF-8?q?=E7=BB=84=E5=90=88=E6=80=BB=E5=92=8CII.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 49acb8d6..de13e031 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -532,6 +532,7 @@ var combinationSum2 = function(candidates, target) { }; ``` **使用used去重** + ```js var combinationSum2 = function(candidates, target) { let res = []; @@ -562,6 +563,37 @@ var combinationSum2 = function(candidates, target) { }; ``` +## TypeScript + +```typescript +function combinationSum2(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const resArr: number[][] = []; + function backTracking( + candidates: number[], target: number, + curSum: number, startIndex: number, route: number[] + ) { + if (curSum > target) return; + if (curSum === target) { + resArr.push(route.slice()); + return; + } + for (let i = startIndex, length = candidates.length; i < length; i++) { + if (i > startIndex && candidates[i] === candidates[i - 1]) { + continue; + } + let tempVal: number = candidates[i]; + route.push(tempVal); + backTracking(candidates, target, curSum + tempVal, i + 1, route); + route.pop(); + + } + } + backTracking(candidates, target, 0, 0, []); + return resArr; +}; +``` + ## C ```c From c569dc505b59552f1435cecc1b584d88417a4cac Mon Sep 17 00:00:00 2001 From: zhujs Date: Tue, 29 Mar 2022 23:33:34 +0800 Subject: [PATCH 230/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200332.=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B=20Go=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/0332.重新安排行程.md | 72 +++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 01f81c4d..e65786c6 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -568,5 +568,77 @@ for line in tickets { } ``` +### Go +```Go + +// 先排序,然后找到第一条路径即可返回 +func findItinerary(tickets [][]string) []string { + var path []string // 用来保存搜索的路径 + data := make(map[string]ticketSlice) // 用来保存tickets排序后的结果 + + var search func(airport string) bool + search = func(airport string) bool { + if len(path) == len(tickets) { + path = append(path, airport) + return true + } + to := data[airport] + for _, item := range to { + if item.Count == 0 { + // 已用完 + continue + } + + path = append(path, airport) + item.Count-- + if search(item.To) { return true } + item.Count++ + path = path[:len(path) - 1] + } + + return false + } + + // 排序 + // 感觉这段代码有点啰嗦,不知道能不能简化一下 + tmp := make(map[string]map[string]int) + for _, ticket := range tickets { + if to, ok := tmp[ticket[0]]; ok { + if _, ok2 := to[ticket[1]]; ok2 { + to[ticket[1]]++ + } else { + to[ticket[1]] = 1 + } + } else { + tmp[ticket[0]] = map[string]int{ + ticket[1]: 1, + } + } + } + for from, to := range tmp { + var tmp ticketSlice + for to, num := range to { + tmp = append(tmp, &ticketStat{To: to, Count: num}) + } + sort.Sort(tmp) + data[from] = tmp + } + + search("JFK") + return path +} + +type ticketStat struct { + To string + Count int +} +type ticketSlice []*ticketStat + +func (p ticketSlice) Len() int { return len(p) } +func (p ticketSlice) Less(i, j int) bool { return strings.Compare(p[i].To, p[j].To) == -1 } +func (p ticketSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +``` + -----------------------

From f0b771af5c8d1fe5d5a298f00a2dbc05a1e23b42 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 30 Mar 2022 16:40:18 +0800 Subject: [PATCH 231/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880131.?= =?UTF-8?q?=E5=88=86=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2.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/0131.分割回文串.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index f50f1c1d..10b747cb 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -450,6 +450,38 @@ var partition = function(s) { }; ``` +## TypeScript + +```typescript +function partition(s: string): string[][] { + function isPalindromeStr(s: string, left: number, right: number): boolean { + while (left < right) { + if (s[left++] !== s[right--]) { + return false; + } + } + return true; + } + function backTracking(s: string, startIndex: number, route: string[]): void { + let length: number = s.length; + if (length === startIndex) { + resArr.push(route.slice()); + return; + } + for (let i = startIndex; i < length; i++) { + if (isPalindromeStr(s, startIndex, i)) { + route.push(s.slice(startIndex, i + 1)); + backTracking(s, i + 1, route); + route.pop(); + } + } + } + const resArr: string[][] = []; + backTracking(s, 0, []); + return resArr; +}; +``` + ## C ```c From 7ee6bdbbfac43194c2ce3d5feb1f322824c3c7c7 Mon Sep 17 00:00:00 2001 From: h-yx-blog <2041290842@qq.com> Date: Thu, 31 Mar 2022 08:59:58 +0800 Subject: [PATCH 232/257] =?UTF-8?q?416=E5=88=86=E5=89=B2=E7=AD=89=E5=92=8C?= =?UTF-8?q?=E5=AD=90=E9=9B=86java=E7=89=88=E5=8F=A6=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0416.分割等和子集.md | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index c8d9bc04..b24fb365 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -208,6 +208,75 @@ class Solution { } ``` +```java +public class Solution { + public static void main(String[] args) { + int num[] = {1,5,11,5}; + canPartition(num); + + } + public static boolean canPartition(int[] nums) { + int len = nums.length; + // 题目已经说非空数组,可以不做非空判断 + int sum = 0; + for (int num : nums) { + sum += num; + } + // 特判:如果是奇数,就不符合要求 + if ((sum %2 ) != 0) { + return false; + } + + int target = sum / 2; //目标背包容量 + // 创建二维状态数组,行:物品索引,列:容量(包括 0) + /* + dp[i][j]表示从数组的 [0, i] 这个子区间内挑选一些正整数 + 每个数只能用一次,使得这些数的和恰好等于 j。 + */ + boolean[][] dp = new boolean[len][target + 1]; + + // 先填表格第 0 行,第 1 个数只能让容积为它自己的背包恰好装满 (这里的dp[][]数组的含义就是“恰好”,所以就算容积比它大的也不要) + if (nums[0] <= target) { + dp[0][nums[0]] = true; + } + // 再填表格后面几行 + //外层遍历物品 + for (int i = 1; i < len; i++) { + //内层遍历背包 + for (int j = 0; j <= target; j++) { + // 直接从上一行先把结果抄下来,然后再修正 + dp[i][j] = dp[i - 1][j]; + + //如果某个物品单独的重量恰好就等于背包的重量,那么也是满足dp数组的定义的 + if (nums[i] == j) { + dp[i][j] = true; + continue; + } + //如果某个物品的重量小于j,那就可以看该物品是否放入背包 + //dp[i - 1][j]表示该物品不放入背包,如果在 [0, i - 1] 这个子区间内已经有一部分元素,使得它们的和为 j ,那么 dp[i][j] = true; + //dp[i - 1][j - nums[i]]表示该物品放入背包。如果在 [0, i - 1] 这个子区间内就得找到一部分元素,使得它们的和为 j - nums[i]。 + if (nums[i] < j) { + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]]; + } + } + } + for (int i = 0; i < len; i++) { + for (int j = 0; j <= target; j++) { + System.out.print(dp[i][j]+" "); + } + System.out.println(); + } + return dp[len - 1][target]; + } +} +//dp数组的打印结果 +false true false false false false false false false false false false +false true false false false true true false false false false false +false true false false false true true false false false false true +false true false false false true true false false false true true +``` + + 二维数组版本(易于理解): ```Java class Solution { From 00dc57faaca1a77fd7c371f2975df5939a7edb0c Mon Sep 17 00:00:00 2001 From: MoonLight-Sherry <3397446353@qq.com> Date: Thu, 31 Mar 2022 10:34:34 +0800 Subject: [PATCH 233/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=860509.?= =?UTF-8?q?=E6=96=90=E6=B3=A2=E9=82=A3=E5=A5=91=E6=95=B0=E5=88=97Rust?= =?UTF-8?q?=E4=B8=A4=E7=A7=8D=E8=A7=A3=E6=B3=95=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0509.斐波那契数.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index c6ce76c0..e60b8a9e 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -277,7 +277,30 @@ int fib(int n){ return fib(n-1) + fib(n-2); } ``` +### Rust +动态规划: +```Rust +pub fn fib(n: i32) -> i32 { + let n = n as usize; + let mut dp = vec![0; 31]; + dp[1] = 1; + for i in 2..=n { + dp[i] = dp[i - 1] + dp[i - 2]; + } + dp[n] +} +``` - +递归实现: +```Rust +pub fn fib(n: i32) -> i32 { + //若n小于等于1,返回n + f n <= 1 { + return n; + } + //否则返回fib(n-1) + fib(n-2) + return fib(n - 1) + fib(n - 2); +} +``` -----------------------
From b6688d7a8949694c2988d48c79f4ebd75d5229ed Mon Sep 17 00:00:00 2001 From: Qianzhengjun <55390356+Qianzhengjun@users.noreply.github.com> Date: Thu, 31 Mar 2022 11:37:47 +0800 Subject: [PATCH 234/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=860844.=20?= =?UTF-8?q?=E6=AF=94=E8=BE=83=E5=90=AB=E9=80=80=E6=A0=BC=E7=9A=84=E5=AD=97?= =?UTF-8?q?=E7=AC=A6=E4=B8=B2=E5=8F=8C=E6=8C=87=E9=92=88=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=9A=84Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0844.比较含退格的字符串.md | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 00d52e42..0d83d425 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -185,6 +185,36 @@ class Solution { } ``` +双指针: + +```java +class Solution { +public static boolean backspaceCompare(String s, String t) { + char[] sarray = s.toCharArray(); + char[] tarray = t.toCharArray(); + return generate(sarray).equals(generate(tarray)); + } + public static String generate(char[] a){ + int slow = -1; + int fast = 0; + if(a.length == 1){ + return new String(a); + } else{ + for(fast = 0; fast < a.length; fast++){ + if(a[fast] != '#') + a[++slow] = a[fast]; + else{ + if(slow >= 0) + slow--; + } + } + return new String(a,0,slow + 1); + } + } +} +``` + + ### python From 6259a0e31769e1dcba1c54b20af6134ed6107120 Mon Sep 17 00:00:00 2001 From: youngyangyang04 <826123027@qq.com> Date: Thu, 31 Mar 2022 15:09:10 +0800 Subject: [PATCH 235/257] remote $ --- problems/0005.最长回文子串.md | 10 ++--- problems/0027.移除元素.md | 16 ++++---- problems/0028.实现strStr.md | 4 +- problems/0042.接雨水.md | 8 ++-- problems/0053.最大子序和.md | 12 +++--- problems/0053.最大子序和(动态规划).md | 4 +- problems/0062.不同路径.md | 14 +++---- problems/0063.不同路径II.md | 4 +- .../0122.买卖股票的最佳时机II(动态规划).md | 8 ++-- problems/0139.单词拆分.md | 10 ++--- problems/0151.翻转字符串里的单词.md | 8 ++-- problems/0189.旋转数组.md | 4 +- problems/0209.长度最小的子数组.md | 16 ++++---- problems/0222.完全二叉树的节点个数.md | 12 +++--- problems/0242.有效的字母异位词.md | 4 +- problems/0283.移动零.md | 2 +- problems/0343.整数拆分.md | 4 +- problems/0349.两个数组的交集.md | 2 +- problems/0406.根据身高重建队列.md | 10 ++--- problems/0435.无重叠区间.md | 4 +- problems/0494.目标和.md | 4 +- problems/0509.斐波那契数.md | 12 +++--- problems/0673.最长递增子序列的个数.md | 6 +-- problems/0714.买卖股票的最佳时机含手续费.md | 12 +++--- problems/0739.每日温度.md | 10 ++--- problems/0746.使用最小花费爬楼梯.md | 8 ++-- problems/0844.比较含退格的字符串.md | 16 ++++---- problems/0922.按奇偶排序数组II.md | 16 ++++---- problems/0925.长按键入.md | 4 +- problems/0977.有序数组的平方.md | 4 +- problems/1049.最后一块石头的重量II.md | 4 +- ...n)的算法居然超时了,此时的n究竟是多大?.md | 18 ++++----- .../关于时间复杂度,你不知道的都在这里!.md | 40 +++++++++---------- problems/剑指Offer05.替换空格.md | 6 +-- problems/动态规划-股票问题总结篇.md | 32 +++++++-------- problems/动态规划理论基础.md | 2 +- problems/双指针总结.md | 16 ++++---- problems/回溯总结.md | 12 +++--- problems/回溯算法去重问题的另一种写法.md | 6 +-- problems/字符串总结.md | 6 +-- problems/数组总结篇.md | 12 +++--- .../根据身高重建队列(vector原理讲解).md | 8 ++-- problems/知识星球精选/刷力扣用不用库函数.md | 2 +- problems/背包问题理论基础多重背包.md | 4 +- problems/链表理论基础.md | 4 +- 45 files changed, 210 insertions(+), 210 deletions(-) diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 8b3af3bb..eaebb5ab 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -38,7 +38,7 @@ 两层for循环,遍历区间起始位置和终止位置,然后判断这个区间是不是回文。 -时间复杂度:$O(n^3)$ +时间复杂度:O(n^3) ## 动态规划 @@ -205,8 +205,8 @@ public: ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n^2)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(n^2) ## 双指针 @@ -253,8 +253,8 @@ public: ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(1) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 3a776837..8d6ca502 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -11,7 +11,7 @@ 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 -不要使用额外的数组空间,你必须仅使用 $O(1)$ 额外空间并**原地**修改输入数组。 +不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并**原地**修改输入数组。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 @@ -42,7 +42,7 @@ ![27.移除元素-暴力解法](https://tva1.sinaimg.cn/large/008eGmZEly1gntrc7x9tjg30du09m1ky.gif) -很明显暴力解法的时间复杂度是$O(n^2)$,这道题目暴力解法在leetcode上是可以过的。 +很明显暴力解法的时间复杂度是O(n^2),这道题目暴力解法在leetcode上是可以过的。 代码如下: @@ -68,8 +68,8 @@ public: }; ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(1) ### 双指针法 @@ -101,16 +101,16 @@ public: ``` 注意这些实现方法并没有改变元素的相对位置! -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 旧文链接:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html) ```CPP /** * 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素 -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) */ class Solution { public: diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index 854789ee..634d8535 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -229,9 +229,9 @@ next数组就可以是前缀表,但是很多实现都是把前缀表统一减 # 时间复杂度分析 -其中n为文本串长度,m为模式串长度,因为在匹配的过程中,根据前缀表不断调整匹配的位置,可以看出匹配的过程是$O(n)$,之前还要单独生成next数组,时间复杂度是$O(m)$。所以整个KMP算法的时间复杂度是$O(n+m)$的。 +其中n为文本串长度,m为模式串长度,因为在匹配的过程中,根据前缀表不断调整匹配的位置,可以看出匹配的过程是O(n),之前还要单独生成next数组,时间复杂度是O(m)。所以整个KMP算法的时间复杂度是O(n+m)的。 -暴力的解法显而易见是$O(n × m)$,所以**KMP在字符串匹配中极大的提高的搜索的效率。** +暴力的解法显而易见是O(n × m),所以**KMP在字符串匹配中极大的提高的搜索的效率。** 为了和力扣题目28.实现strStr保持一致,方便大家理解,以下文章统称haystack为文本串, needle为模式串。 diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index 75152eb7..b232ce22 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -129,8 +129,8 @@ public: }; ``` -因为每次遍历列的时候,还要向两边寻找最高的列,所以时间复杂度为$O(n^2)$。 -空间复杂度为$O(1)$。 +因为每次遍历列的时候,还要向两边寻找最高的列,所以时间复杂度为O(n^2)。 +空间复杂度为O(1)。 @@ -779,8 +779,8 @@ int trap(int* height, int heightSize) { } ``` -* 时间复杂度 $O(n)$ -* 空间复杂度 $O(1)$ +* 时间复杂度 O(n) +* 空间复杂度 O(1) ----------------------- diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index d699d49a..3d11c91e 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -21,8 +21,8 @@ 暴力解法的思路,第一层for 就是设置起始位置,第二层for循环遍历数组寻找最大值 -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(1) ```CPP class Solution { @@ -98,8 +98,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 当然题目没有说如果数组为空,应该返回什么,所以数组为空的话返回啥都可以了。 @@ -128,8 +128,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 总结 diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index 703e1dd6..4c883cb6 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -80,8 +80,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 总结 diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index efa85a03..4a9af129 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -80,7 +80,7 @@ public: 那二叉树的节点个数就是 2^(m + n - 1) - 1。可以理解深搜的算法就是遍历了整个满二叉树(其实没有遍历整个满二叉树,只是近似而已) -所以上面深搜代码的时间复杂度为$O(2^{m + n - 1} - 1)$,可以看出,这是指数级别的时间复杂度,是非常大的。 +所以上面深搜代码的时间复杂度为O(2^(m + n - 1) - 1),可以看出,这是指数级别的时间复杂度,是非常大的。 ### 动态规划 @@ -143,8 +143,8 @@ public: }; ``` -* 时间复杂度:$O(m × n)$ -* 空间复杂度:$O(m × n)$ +* 时间复杂度:O(m × n) +* 空间复杂度:O(m × n) 其实用一个一维数组(也可以理解是滚动数组)就可以了,但是不利于理解,可以优化点空间,建议先理解了二维,在理解一维,C++代码如下: @@ -164,8 +164,8 @@ public: }; ``` -* 时间复杂度:$O(m × n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(m × n) +* 空间复杂度:O(n) ### 数论方法 @@ -224,8 +224,8 @@ public: }; ``` -* 时间复杂度:$O(m)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(m) +* 空间复杂度:O(1) **计算组合问题的代码还是有难度的,特别是处理溢出的情况!** diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 8e82007e..34df05d8 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -152,8 +152,8 @@ public: }; ``` -* 时间复杂度:$O(n × m)$,n、m 分别为obstacleGrid 长度和宽度 -* 空间复杂度:$O(n × m)$ +* 时间复杂度:O(n × m),n、m 分别为obstacleGrid 长度和宽度 +* 空间复杂度:O(n × m) ## 总结 diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index e5fdd53d..615d79bb 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -88,8 +88,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 大家可以本题和[121. 买卖股票的最佳时机](https://programmercarl.com/0121.买卖股票的最佳时机.html)的代码几乎一样,唯一的区别在: @@ -121,8 +121,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index e04cb173..c087183a 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -66,8 +66,8 @@ public: }; ``` -* 时间复杂度:$O(2^n)$,因为每一个单词都有两个状态,切割和不切割 -* 空间复杂度:$O(n)$,算法递归系统调用栈的空间 +* 时间复杂度:O(2^n),因为每一个单词都有两个状态,切割和不切割 +* 空间复杂度:O(n),算法递归系统调用栈的空间 那么以上代码很明显要超时了,超时的数据如下: @@ -114,7 +114,7 @@ public: }; ``` -这个时间复杂度其实也是:$O(2^n)$。只不过对于上面那个超时测试用例优化效果特别明显。 +这个时间复杂度其实也是:O(2^n)。只不过对于上面那个超时测试用例优化效果特别明显。 **这个代码就可以AC了,当然回溯算法不是本题的主菜,背包才是!** @@ -207,8 +207,8 @@ public: }; ``` -* 时间复杂度:$O(n^3)$,因为substr返回子串的副本是$O(n)$的复杂度(这里的n是substring的长度) -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n^3),因为substr返回子串的副本是$O(n)$的复杂度(这里的n是substring的长度) +* 空间复杂度:O(n) ## 总结 diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 7588cbd6..8dfe9bbc 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -36,7 +36,7 @@ 一些同学会使用split库函数,分隔单词,然后定义一个新的string字符串,最后再把单词倒序相加,那么这道题题目就是一道水题了,失去了它的意义。 -所以这里我还是提高一下本题的难度:**不要使用辅助空间,空间复杂度要求为$O(1)$。** +所以这里我还是提高一下本题的难度:**不要使用辅助空间,空间复杂度要求为O(1)。** 不能使用辅助空间之后,那么只能在原字符串上下功夫了。 @@ -81,11 +81,11 @@ void removeExtraSpaces(string& s) { 如果不仔细琢磨一下erase的时间复杂读,还以为以上的代码是$O(n)$的时间复杂度呢。 -想一下真正的时间复杂度是多少,一个erase本来就是$O(n)$的操作,erase实现原理题目:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html),最优的算法来移除元素也要$O(n)$。 +想一下真正的时间复杂度是多少,一个erase本来就是O(n)的操作,erase实现原理题目:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html),最优的算法来移除元素也要O(n)。 -erase操作上面还套了一个for循环,那么以上代码移除冗余空格的代码时间复杂度为$O(n^2)$。 +erase操作上面还套了一个for循环,那么以上代码移除冗余空格的代码时间复杂度为O(n^2)。 -那么使用双指针法来去移除空格,最后resize(重新设置)一下字符串的大小,就可以做到$O(n)$的时间复杂度。 +那么使用双指针法来去移除空格,最后resize(重新设置)一下字符串的大小,就可以做到O(n)的时间复杂度。 如果对这个操作比较生疏了,可以再看一下这篇文章:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html)是如何移除元素的。 diff --git a/problems/0189.旋转数组.md b/problems/0189.旋转数组.md index bbe152a2..1efe9446 100644 --- a/problems/0189.旋转数组.md +++ b/problems/0189.旋转数组.md @@ -12,7 +12,7 @@ 进阶: 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。 -你可以使用空间复杂度为 $O(1)$ 的 原地 算法解决这个问题吗? +你可以使用空间复杂度为 O(1) 的 原地 算法解决这个问题吗? 示例 1: @@ -41,7 +41,7 @@ 本题其实和[字符串:剑指Offer58-II.左旋转字符串](https://programmercarl.com/剑指Offer58-II.左旋转字符串.html)就非常像了,剑指offer上左旋转,本题是右旋转。 -注意题目要求是**要求使用空间复杂度为 $O(1)$ 的 原地 算法** +注意题目要求是**要求使用空间复杂度为 O(1) 的 原地 算法** 那么我来提供一种旋转的方式哈。 diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index dc1d9f18..82a11381 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -20,7 +20,7 @@ ## 暴力解法 -这道题目暴力解法当然是 两个for循环,然后不断的寻找符合条件的子序列,时间复杂度很明显是$O(n^2)$。 +这道题目暴力解法当然是 两个for循环,然后不断的寻找符合条件的子序列,时间复杂度很明显是O(n^2)。 代码如下: @@ -47,8 +47,8 @@ public: } }; ``` -时间复杂度:$O(n^2)$ -空间复杂度:$O(1)$ +时间复杂度:O(n^2) +空间复杂度:O(1) ## 滑动窗口 @@ -80,7 +80,7 @@ public: ![leetcode_209](https://img-blog.csdnimg.cn/20210312160441942.png) -可以发现**滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将$O(n^2)$的暴力解法降为$O(n)$。** +可以发现**滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)暴力解法降为O(n)。** C++代码如下: @@ -107,12 +107,12 @@ public: }; ``` -时间复杂度:$O(n)$ -空间复杂度:$O(1)$ +时间复杂度:O(n) +空间复杂度:O(1) -**一些录友会疑惑为什么时间复杂度是$O(n)$**。 +**一些录友会疑惑为什么时间复杂度是O(n)**。 -不要以为for里放一个while就以为是$O(n^2)$啊, 主要是看每一个元素被操作的次数,每个元素在滑动窗后进来操作一次,出去操作一次,每个元素都是被被操作两次,所以时间复杂度是 2 × n 也就是$O(n)$。 +不要以为for里放一个while就以为是O(n^2)啊, 主要是看每一个元素被操作的次数,每个元素在滑动窗后进来操作一次,出去操作一次,每个元素都是被被操作两次,所以时间复杂度是 2 × n 也就是O(n)。 ## 相关题目推荐 diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index ffbc32ff..ba7acc5a 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -105,8 +105,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(\log n)$,算上了递归系统栈占用的空间 +* 时间复杂度:O(n) +* 空间复杂度:O(log n),算上了递归系统栈占用的空间 **网上基本都是这个精简的代码版本,其实不建议大家照着这个来写,代码确实精简,但隐藏了一些内容,连遍历的顺序都看不出来,所以初学者建议学习版本一的代码,稳稳的打基础**。 @@ -138,8 +138,8 @@ public: } }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 完全二叉树 @@ -185,8 +185,8 @@ public: }; ``` -* 时间复杂度:$O(\log n × \log n)$ -* 空间复杂度:$O(\log n)$ +* 时间复杂度:O(log n × log n) +* 空间复杂度:O(log n) # 其他语言版本 diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 52f8e667..080166fd 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -27,7 +27,7 @@ ## 思路 -先看暴力的解法,两层for循环,同时还要记录字符是否重复出现,很明显时间复杂度是 $O(n^2)$。 +先看暴力的解法,两层for循环,同时还要记录字符是否重复出现,很明显时间复杂度是 O(n^2)。 暴力的方法这里就不做介绍了,直接看一下有没有更优的方式。 @@ -55,7 +55,7 @@ 最后如果record数组所有元素都为零0,说明字符串s和t是字母异位词,return true。 -时间复杂度为$O(n)$,空间上因为定义是的一个常量大小的辅助数组,所以空间复杂度为$O(1)$。 +时间复杂度为O(n),空间上因为定义是的一个常量大小的辅助数组,所以空间复杂度为O(1)。 C++ 代码如下: diff --git a/problems/0283.移动零.md b/problems/0283.移动零.md index bb75a696..ed59d2c4 100644 --- a/problems/0283.移动零.md +++ b/problems/0283.移动零.md @@ -30,7 +30,7 @@ 好了,我们说一说双指针法,大家如果对双指针还不熟悉,可以看我的这篇总结[双指针法:总结篇!](https://programmercarl.com/双指针总结.html)。 -双指针法在数组移除元素中,可以达到$O(n)$的时间复杂度,在[27.移除元素](https://programmercarl.com/0027.移除元素.html)里已经详细讲解了,那么本题和移除元素其实是一个套路。 +双指针法在数组移除元素中,可以达到O(n)的时间复杂度,在[27.移除元素](https://programmercarl.com/0027.移除元素.html)里已经详细讲解了,那么本题和移除元素其实是一个套路。 **相当于对整个数组移除元素0,然后slowIndex之后都是移除元素0的冗余元素,把这些元素都赋值为0就可以了**。 diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index b6182ed6..777146ba 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -148,8 +148,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) ## 总结 diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 92342f17..82be1829 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -28,7 +28,7 @@ 注意题目特意说明:**输出结果中的每个元素一定是唯一的,也就是说输出的结果的去重的, 同时可以不考虑输出结果的顺序** -这道题用暴力的解法时间复杂度是$O(n^2)$,那来看看使用哈希法进一步优化。 +这道题用暴力的解法时间复杂度是O(n^2),那来看看使用哈希法进一步优化。 那么用数组来做哈希表也是不错的选择,例如[242. 有效的字母异位词](https://programmercarl.com/0242.有效的字母异位词.html) diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index 28eb5744..b2354d09 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -116,12 +116,12 @@ public: } }; ``` -* 时间复杂度:$O(n\log n + n^2)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(nlog n + n^2) +* 空间复杂度:O(n) 但使用vector是非常费时的,C++中vector(可以理解是一个动态数组,底层是普通数组实现的)如果插入元素大于预先普通数组大小,vector底部会有一个扩容的操作,即申请两倍于原先普通数组的大小,然后把数据拷贝到另一个更大的数组上。 -所以使用vector(动态数组)来insert,是费时的,插入再拷贝的话,单纯一个插入的操作就是$O(n^2)$了,甚至可能拷贝好几次,就不止$O(n^2)$了。 +所以使用vector(动态数组)来insert,是费时的,插入再拷贝的话,单纯一个插入的操作就是O(n^2)了,甚至可能拷贝好几次,就不止O(n^2)了。 改成链表之后,C++代码如下: @@ -150,8 +150,8 @@ public: }; ``` -* 时间复杂度:$O(n\log n + n^2)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(nlog n + n^2) +* 空间复杂度:O(n) 大家可以把两个版本的代码提交一下试试,就可以发现其差别了! diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 389443d1..b24ca024 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -92,8 +92,8 @@ public: } }; ``` -* 时间复杂度:$O(n\log n)$ ,有一个快排 -* 空间复杂度:$O(1)$ +* 时间复杂度:O(nlog n) ,有一个快排 +* 空间复杂度:O(1) 大家此时会发现如此复杂的一个问题,代码实现却这么简单! diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index df667a85..99b76834 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -225,8 +225,8 @@ public: }; ``` -* 时间复杂度:$O(n × m)$,n为正数个数,m为背包容量 -* 空间复杂度:$O(m)$,m为背包容量 +* 时间复杂度:O(n × m),n为正数个数,m为背包容量 +* 空间复杂度:O(m),m为背包容量 ## 总结 diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index c6ce76c0..638bfdfe 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -101,8 +101,8 @@ public: } }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 当然可以发现,我们只需要维护两个数值就可以了,不需要记录整个序列。 @@ -126,8 +126,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) ### 递归解法 @@ -145,8 +145,8 @@ public: }; ``` -* 时间复杂度:$O(2^n)$ -* 空间复杂度:$O(n)$,算上了编程语言中实现递归的系统栈所占空间 +* 时间复杂度:O(2^n) +* 空间复杂度:O(n),算上了编程语言中实现递归的系统栈所占空间 这个递归的时间复杂度大家画一下树形图就知道了,如果不清晰的同学,可以看这篇:[通过一道面试题目,讲一讲递归算法的时间复杂度!](https://programmercarl.com/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.html) diff --git a/problems/0673.最长递增子序列的个数.md b/problems/0673.最长递增子序列的个数.md index 7ea91e97..9a2c5db2 100644 --- a/problems/0673.最长递增子序列的个数.md +++ b/problems/0673.最长递增子序列的个数.md @@ -216,10 +216,10 @@ public: }; ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(n) -还有$O(n\log n)$的解法,使用树状数组,今天有点忙就先不写了,感兴趣的同学可以自行学习一下,这里有我之前写的树状数组系列博客:https://blog.csdn.net/youngyangyang04/category_871105.html (十年前的陈年老文了) +还有O(nlog n)的解法,使用树状数组,今天有点忙就先不写了,感兴趣的同学可以自行学习一下,这里有我之前写的树状数组系列博客:https://blog.csdn.net/youngyangyang04/category_871105.html (十年前的陈年老文了) # 其他语言版本 diff --git a/problems/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index fd42691b..2f27d6ea 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -84,8 +84,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 从代码中可以看出对情况一的操作,因为如果还在收获利润的区间里,表示并不是真正的卖出,而计算利润每次都要减去手续费,**所以要让minPrice = prices[i] - fee;,这样在明天收获利润的时候,才不会多减一次手续费!** @@ -117,8 +117,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 当然可以对空间经行优化,因为当前状态只是依赖前一个状态。 @@ -141,8 +141,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) ## 总结 diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index bdc75b96..710f5eb6 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -18,7 +18,7 @@ ## 思路 -首先想到的当然是暴力解法,两层for循环,把至少需要等待的天数就搜出来了。时间复杂度是$O(n^2)$ +首先想到的当然是暴力解法,两层for循环,把至少需要等待的天数就搜出来了。时间复杂度是O(n^2) 那么接下来在来看看使用单调栈的解法。 @@ -26,13 +26,13 @@ **通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了**。 -时间复杂度为$O(n)$。 +时间复杂度为O(n)。 例如本题其实就是找找到一个元素右边第一个比自己大的元素。 此时就应该想到用单调栈了。 -那么单调栈的原理是什么呢?为什么时间复杂度是$O(n)$就可以找到每一个元素的右边第一个比它大的元素位置呢? +那么单调栈的原理是什么呢?为什么时间复杂度是O(n)就可以找到每一个元素的右边第一个比它大的元素位置呢? 单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素的元素,优点是只需要遍历一次。 @@ -164,8 +164,8 @@ public: } }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 精简的代码是直接把情况一二三都合并到了一起,其实这种代码精简是精简,但思路不是很清晰。 diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index e94e4d24..c356955a 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -113,8 +113,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 还可以优化空间复杂度,因为dp[i]就是由前两位推出来的,那么也不用dp数组了,C++代码如下: @@ -136,8 +136,8 @@ public: ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) **当然我不建议这么写,能写出版本一就可以了,直观简洁!** diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 00d52e42..3bbfb73e 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -36,7 +36,7 @@ ## 思路 -本文将给出 空间复杂度$O(n)$的栈模拟方法 以及空间复杂度是$O(1)$的双指针方法。 +本文将给出 空间复杂度O(n)的栈模拟方法 以及空间复杂度是O(1)的双指针方法。 ## 普通方法(使用栈的思路) @@ -71,8 +71,8 @@ public: } }; ``` -* 时间复杂度:$O(n + m)$,n为S的长度,m为T的长度 ,也可以理解是$O(n)$的时间复杂度 -* 空间复杂度:$O(n + m)$ +* 时间复杂度:O(n + m),n为S的长度,m为T的长度 ,也可以理解是$O(n)$的时间复杂度 +* 空间复杂度:O(n + m) 当然以上代码,大家可以发现有重复的逻辑处理S,处理T,可以把这块公共逻辑抽离出来,代码精简如下: @@ -97,12 +97,12 @@ public: ``` 性能依然是: -* 时间复杂度:$O(n + m)$ -* 空间复杂度:$O(n + m)$ +* 时间复杂度:O(n + m) +* 空间复杂度:O(n + m) ## 优化方法(从后向前双指针) -当然还可以有使用 $O(1)$ 的空间复杂度来解决该问题。 +当然还可以有使用 O(1) 的空间复杂度来解决该问题。 同时从后向前遍历S和T(i初始为S末尾,j初始为T末尾),记录#的数量,模拟消除的操作,如果#用完了,就开始比较S[i]和S[j]。 @@ -151,8 +151,8 @@ public: }; ``` -* 时间复杂度:$O(n + m)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n + m) +* 空间复杂度:O(1) ## 其他语言版本 diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 19675e7f..4ff419d3 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -26,11 +26,11 @@ ## 思路 -这道题目直接的想法可能是两层for循环再加上used数组表示使用过的元素。这样的的时间复杂度是$O(n^2)$。 +这道题目直接的想法可能是两层for循环再加上used数组表示使用过的元素。这样的的时间复杂度是O(n^2)。 ### 方法一 -其实这道题可以用很朴实的方法,时间复杂度就就是$O(n)$了,C++代码如下: +其实这道题可以用很朴实的方法,时间复杂度就就是O(n)了,C++代码如下: ```CPP class Solution { @@ -57,8 +57,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ### 方法二 @@ -86,8 +86,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ### 方法三 @@ -109,8 +109,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 这里时间复杂度并不是$O(n^2)$,因为偶数位和奇数位都只操作一次,不是n/2 * n/2的关系,而是n/2 + n/2的关系! diff --git a/problems/0925.长按键入.md b/problems/0925.长按键入.md index 3aacee5c..0ef5a3d7 100644 --- a/problems/0925.长按键入.md +++ b/problems/0925.长按键入.md @@ -90,8 +90,8 @@ public: ``` -时间复杂度:$O(n)$ -空间复杂度:$O(1)$ +时间复杂度:O(n) +空间复杂度:O(1) ## 其他语言版本 diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index b11fa7ef..24276bcf 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -40,7 +40,7 @@ public: }; ``` -这个时间复杂度是 $O(n + n\log n)$, 可以说是$O(n\log n)$的时间复杂度,但为了和下面双指针法算法时间复杂度有鲜明对比,我记为 $O(n + n\log n)$。 +这个时间复杂度是 O(n + nlogn), 可以说是O(nlogn)的时间复杂度,但为了和下面双指针法算法时间复杂度有鲜明对比,我记为 O(n + nlog n)。 ## 双指针法 @@ -83,7 +83,7 @@ public: }; ``` -此时的时间复杂度为$O(n)$,相对于暴力排序的解法$O(n + n\log n)$还是提升不少的。 +此时的时间复杂度为O(n),相对于暴力排序的解法O(n + nlog n)还是提升不少的。 **这里还是说一下,大家不必太在意leetcode上执行用时,打败多少多少用户,这个就是一个玩具,非常不准确。** diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 7b67b1ac..ee0ddef2 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -136,8 +136,8 @@ public: ``` -* 时间复杂度:$O(m × n)$ , m是石头总重量(准确的说是总重量的一半),n为石头块数 -* 空间复杂度:$O(m)$ +* 时间复杂度:O(m × n) , m是石头总重量(准确的说是总重量的一半),n为石头块数 +* 空间复杂度:O(m) ## 总结 diff --git a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md index 4de56597..75f441db 100644 --- a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md @@ -3,7 +3,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-# 程序提交之后为什么会超时?$O(n)$的算法会超时,n究竟是多大? +# 程序提交之后为什么会超时?O(n)的算法会超时,n究竟是多大? 一些同学可能对计算机运行的速度还没有概念,就是感觉计算机运行速度应该会很快,那么在leetcode上做算法题目的时候为什么会超时呢? @@ -18,9 +18,9 @@ 也就是说程序运行的时间超过了规定的时间,一般OJ(online judge)的超时时间就是1s,也就是用例数据输入后最多要1s内得到结果,暂时还不清楚leetcode的判题规则,下文为了方便讲解,暂定超时时间就是1s。 -如果写出了一个$O(n)$的算法 ,其实可以估算出来n是多大的时候算法的执行时间就会超过1s了。 +如果写出了一个O(n)的算法 ,其实可以估算出来n是多大的时候算法的执行时间就会超过1s了。 -如果n的规模已经足够让$O(n)$的算法运行时间超过了1s,就应该考虑log(n)的解法了。 +如果n的规模已经足够让O(n)的算法运行时间超过了1s,就应该考虑log(n)的解法了。 # 从硬件配置看计算机的性能 @@ -63,7 +63,7 @@ 测试硬件:2015年MacPro,CPU配置:2.7 GHz Dual-Core Intel Core i5 -实现三个函数,时间复杂度分别是 $O(n)$ , $O(n^2)$, $O(n\log n)$,使用加法运算来统一测试。 +实现三个函数,时间复杂度分别是 O(n) , O(n^2), O(nlog n),使用加法运算来统一测试。 ```CPP // O(n) @@ -128,19 +128,19 @@ int main() { ![程序超时2](https://img-blog.csdnimg.cn/20200729200018460.png) -O(n)的算法,1s内大概计算机可以运行 5 * (10^8)次计算,可以推测一下$O(n^2)$ 的算法应该1s可以处理的数量级的规模是 5 * (10^8)开根号,实验数据如下。 +O(n)的算法,1s内大概计算机可以运行 5 * (10^8)次计算,可以推测一下O(n^2) 的算法应该1s可以处理的数量级的规模是 5 * (10^8)开根号,实验数据如下。 ![程序超时3](https://img-blog.csdnimg.cn/2020072919590970.png) O(n^2)的算法,1s内大概计算机可以运行 22500次计算,验证了刚刚的推测。 -在推测一下$O(n\log n)$的话, 1s可以处理的数据规模是什么呢? +在推测一下O(nlogn)的话, 1s可以处理的数据规模是什么呢? -理论上应该是比 $O(n)$少一个数量级,因为$\log n$的复杂度 其实是很快,看一下实验数据。 +理论上应该是比 O(n)少一个数量级,因为logn的复杂度 其实是很快,看一下实验数据。 ![程序超时4](https://img-blog.csdnimg.cn/20200729195729407.png) -$O(n \logn)$的算法,1s内大概计算机可以运行 2 * (10^7)次计算,符合预期。 +O(nlogn)的算法,1s内大概计算机可以运行 2 * (10^7)次计算,符合预期。 这是在我个人PC上测出来的数据,不能说是十分精确,但数量级是差不多的,大家也可以在自己的计算机上测一下。 @@ -209,7 +209,7 @@ int main() { # 总结 -本文详细分析了在leetcode上做题程序为什么会有超时,以及从硬件配置上大体知道CPU的执行速度,然后亲自做一个实验来看看$O(n)$的算法,跑一秒钟,这个n究竟是做大,最后给出不同时间复杂度,一秒内可以运算出来的n的大小。 +本文详细分析了在leetcode上做题程序为什么会有超时,以及从硬件配置上大体知道CPU的执行速度,然后亲自做一个实验来看看O(n)的算法,跑一秒钟,这个n究竟是做大,最后给出不同时间复杂度,一秒内可以运算出来的n的大小。 建议录友们也都自己做一做实验,测一测,看看是不是和我的测出来的结果差不多。 diff --git a/problems/关于时间复杂度,你不知道的都在这里!.md b/problems/关于时间复杂度,你不知道的都在这里!.md index b6477249..77fdacc4 100644 --- a/problems/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/关于时间复杂度,你不知道的都在这里!.md @@ -16,21 +16,21 @@ 那么该如何估计程序运行时间呢,通常会估算算法的操作单元数量来代表程序消耗的时间,这里默认CPU的每个单元运行消耗的时间都是相同的。 -假设算法的问题规模为n,那么操作单元数量便用函数f(n)来表示,随着数据规模n的增大,算法执行时间的增长率和f(n)的增长率相同,这称作为算法的渐近时间复杂度,简称时间复杂度,记为 $O(f(n))$。 +假设算法的问题规模为n,那么操作单元数量便用函数f(n)来表示,随着数据规模n的增大,算法执行时间的增长率和f(n)的增长率相同,这称作为算法的渐近时间复杂度,简称时间复杂度,记为 O(f(n))。 ## 什么是大O -这里的大O是指什么呢,说到时间复杂度,**大家都知道$O(n)$,$O(n^2)$,却说不清什么是大O**。 +这里的大O是指什么呢,说到时间复杂度,**大家都知道O(n),O(n^2),却说不清什么是大O**。 算法导论给出的解释:**大O用来表示上界的**,当用它作为算法的最坏情况运行时间的上界,就是对任意数据输入的运行时间的上界。 同样算法导论给出了例子:拿插入排序来说,插入排序的时间复杂度我们都说是$O(n^2)$ 。 -输入数据的形式对程序运算时间是有很大影响的,在数据本来有序的情况下时间复杂度是$O(n)$,但如果数据是逆序的话,插入排序的时间复杂度就是$O(n^2)$,也就对于所有输入情况来说,最坏是$O(n^2)$ 的时间复杂度,所以称插入排序的时间复杂度为$O(n^2)$。 +输入数据的形式对程序运算时间是有很大影响的,在数据本来有序的情况下时间复杂度是O(n),但如果数据是逆序的话,插入排序的时间复杂度就是O(n^2),也就对于所有输入情况来说,最坏是O(n^2) 的时间复杂度,所以称插入排序的时间复杂度为O(n^2)。 -同样的同理再看一下快速排序,都知道快速排序是$O(n\log n)$,但是当数据已经有序情况下,快速排序的时间复杂度是$O(n^2)$ 的,**所以严格从大O的定义来讲,快速排序的时间复杂度应该是$O(n^2)$**。 +同样的同理再看一下快速排序,都知道快速排序是O(nlog n),但是当数据已经有序情况下,快速排序的时间复杂度是O(n^2) 的,**所以严格从大O的定义来讲,快速排序的时间复杂度应该是O(n^2)**。 -**但是我们依然说快速排序是$O(n\log n)$的时间复杂度,这个就是业内的一个默认规定,这里说的O代表的就是一般情况,而不是严格的上界**。如图所示: +**但是我们依然说快速排序是O(nlog n)的时间复杂度,这个就是业内的一个默认规定,这里说的O代表的就是一般情况,而不是严格的上界**。如图所示: ![时间复杂度4,一般情况下的时间复杂度](https://img-blog.csdnimg.cn/20200728185745611.png) 我们主要关心的还是一般情况下的数据形式。 @@ -46,9 +46,9 @@ 在决定使用哪些算法的时候,不是时间复杂越低的越好(因为简化后的时间复杂度忽略了常数项等等),要考虑数据规模,如果数据规模很小甚至可以用$O(n^2)$的算法比$O(n)$的更合适(在有常数项的时候)。 -就像上图中 $O(5n^2)$ 和 $O(100n)$ 在n为20之前 很明显 $O(5n^2)$是更优的,所花费的时间也是最少的。 +就像上图中 O(5n^2) 和 O(100n) 在n为20之前 很明显 O(5n^2)是更优的,所花费的时间也是最少的。 -那为什么在计算时间复杂度的时候要忽略常数项系数呢,也就说$O(100n)$ 就是$O(n)$的时间复杂度,$O(5n^2)$ 就是$O(n^2)$的时间复杂度,而且要默认$O(n)$ 优于$O(n^2)$ 呢 ? +那为什么在计算时间复杂度的时候要忽略常数项系数呢,也就说O(100n) 就是O(n)的时间复杂度,O(5n^2) 就是O(n^2)的时间复杂度,而且要默认O(n) 优于O(n^2) 呢 ? 这里就又涉及到大O的定义,**因为大O就是数据量级突破一个点且数据量级非常大的情况下所表现出的时间复杂度,这个数据量也就是常数项系数已经不起决定性作用的数据量**。 @@ -56,13 +56,13 @@ **所以我们说的时间复杂度都是省略常数项系数的,是因为一般情况下都是默认数据规模足够的大,基于这样的事实,给出的算法时间复杂的的一个排行如下所示**: -O(1) 常数阶 < $O(\log n)$ 对数阶 < $O(n)$ 线性阶 < $O(n^2)$ 平方阶 < $O(n^3)$ 立方阶 < $O(2^n)$指数阶 +O(1) 常数阶 < O(\log n) 对数阶 < O(n) 线性阶 < O(n^2) 平方阶 < O(n^3) 立方阶 < O(2^n)指数阶 但是也要注意大常数,如果这个常数非常大,例如10^7 ,10^9 ,那么常数就是不得不考虑的因素了。 ## 复杂表达式的化简 -有时候我们去计算时间复杂度的时候发现不是一个简单的$O(n)$ 或者$O(n^2)$, 而是一个复杂的表达式,例如: +有时候我们去计算时间复杂度的时候发现不是一个简单的O(n) 或者O(n^2), 而是一个复杂的表达式,例如: ``` O(2*n^2 + 10*n + 1000) @@ -88,19 +88,19 @@ O(n^2 + n) O(n^2) ``` -如果这一步理解有困难,那也可以做提取n的操作,变成$O(n(n+1))$,省略加法常数项后也就别变成了: +如果这一步理解有困难,那也可以做提取n的操作,变成O(n(n+1)),省略加法常数项后也就别变成了: ``` O(n^2) ``` -所以最后我们说:这个算法的算法时间复杂度是$O(n^2)$ 。 +所以最后我们说:这个算法的算法时间复杂度是O(n^2) 。 -也可以用另一种简化的思路,其实当n大于40的时候, 这个复杂度会恒小于$O(3 × n^2)$, -$O(2 × n^2 + 10 × n + 1000)$ < $O(3 × n^2)$,所以说最后省略掉常数项系数最终时间复杂度也是$O(n^2)$。 +也可以用另一种简化的思路,其实当n大于40的时候, 这个复杂度会恒小于O(3 × n^2), +O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项系数最终时间复杂度也是O(n^2)。 -## $O(\log n)$中的log是以什么为底? +## O(log n)中的log是以什么为底? 平时说这个算法的时间复杂度是logn的,那么一定是log 以2为底n的对数么? @@ -123,21 +123,21 @@ $O(2 × n^2 + 10 × n + 1000)$ < $O(3 × n^2)$,所以说最后省略掉常数 通过这道面试题目,来分析一下时间复杂度。题目描述:找出n个字符串中相同的两个字符串(假设这里只有两个相同的字符串)。 -如果是暴力枚举的话,时间复杂度是多少呢,是$O(n^2)$么? +如果是暴力枚举的话,时间复杂度是多少呢,是O(n^2)么? -这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了$n^2$次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是$O(m × n × n)$。 +这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了n^2次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是$O(m × n × n)$。 接下来再想一下其他解题思路。 先排对n个字符串按字典序来排序,排序后n个字符串就是有序的,意味着两个相同的字符串就是挨在一起,然后在遍历一遍n个字符串,这样就找到两个相同的字符串了。 -那看看这种算法的时间复杂度,快速排序时间复杂度为$O(n\log n)$,依然要考虑字符串的长度是m,那么快速排序每次的比较都要有m次的字符比较的操作,就是$O(m × n × \log n)$。 +那看看这种算法的时间复杂度,快速排序时间复杂度为O(nlog n),依然要考虑字符串的长度是m,那么快速排序每次的比较都要有m次的字符比较的操作,就是O(m × n × log n)。 -之后还要遍历一遍这n个字符串找出两个相同的字符串,别忘了遍历的时候依然要比较字符串,所以总共的时间复杂度是 $O(m × n × \log n + n × m)$。 +之后还要遍历一遍这n个字符串找出两个相同的字符串,别忘了遍历的时候依然要比较字符串,所以总共的时间复杂度是 O(m × n × log n + n × m)。 -我们对$O(m × n × \log n + n × m)$进行简化操作,把$m × n$提取出来变成$O(m × n × (\log n + 1)$),再省略常数项最后的时间复杂度是$O(m × n × \log n)$。 +我们对O(m × n × log n + n × m)进行简化操作,把m × n提取出来变成O(m × n × (log n + 1)),再省略常数项最后的时间复杂度是O(m × n × log n)。 -最后很明显$O(m × n × \log n)$ 要优于$O(m × n × n)$! +最后很明显O(m × n × log n) 要优于O(m × n × n)! 所以先把字符串集合排序再遍历一遍找到两个相同字符串的方法要比直接暴力枚举的方式更快。 diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 21fc0602..037bd427 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -29,7 +29,7 @@ i指向新长度的末尾,j指向旧长度的末尾。 有同学问了,为什么要从后向前填充,从前向后填充不行么? -从前向后填充就是$O(n^2)$的算法了,因为每次添加元素都要将添加元素之后的所有元素向后移动。 +从前向后填充就是O(n^2)的算法了,因为每次添加元素都要将添加元素之后的所有元素向后移动。 **其实很多数组填充类的问题,都可以先预先给数组扩容带填充后的大小,然后在从后向前进行操作。** @@ -74,8 +74,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 此时算上本题,我们已经做了七道双指针相关的题目了分别是: diff --git a/problems/动态规划-股票问题总结篇.md b/problems/动态规划-股票问题总结篇.md index e1fb477b..47a9b34b 100644 --- a/problems/动态规划-股票问题总结篇.md +++ b/problems/动态规划-股票问题总结篇.md @@ -72,8 +72,8 @@ public: } }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 使用滚动数组,代码如下: @@ -95,8 +95,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) ## 买卖股票的最佳时机II @@ -121,8 +121,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 【动态规划】 @@ -162,8 +162,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 买卖股票的最佳时机III @@ -226,8 +226,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n × 5)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n × 5) 当然,大家可以看到力扣官方题解里的一种优化空间写法,我这里给出对应的C++版本: @@ -251,8 +251,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) **这种写法看上去简单,其实思路很绕,不建议大家这么写,这么思考,很容易把自己绕进去!** 对于本题,把版本一的写法研究明白,足以! @@ -404,8 +404,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 买卖股票的最佳时机含手续费 @@ -456,8 +456,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 总结 diff --git a/problems/动态规划理论基础.md b/problems/动态规划理论基础.md index e94295a5..66971fce 100644 --- a/problems/动态规划理论基础.md +++ b/problems/动态规划理论基础.md @@ -16,7 +16,7 @@ 所以动态规划中每一个状态一定是由上一个状态推导出来的,**这一点就区分于贪心**,贪心没有状态推导,而是从局部直接选最优的, -在[关于贪心算法,你该了解这些!](https://mp.weixin.qq.com/s/A9MHJi1a5uugFaqp8QJFWg)中我举了一个背包问题的例子。 +在[关于贪心算法,你该了解这些!](https://programmercarl.com/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html)中我举了一个背包问题的例子。 例如:有N件物品和一个最多能背重量为W 的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。**每件物品只能用一次**,求解将哪些物品装入背包里物品价值总和最大。 diff --git a/problems/双指针总结.md b/problems/双指针总结.md index e866aa66..39096ff7 100644 --- a/problems/双指针总结.md +++ b/problems/双指针总结.md @@ -22,7 +22,7 @@ for (int i = 0; i < array.size(); i++) { } ``` -这个代码看上去好像是$O(n)$的时间复杂度,其实是$O(n^2)$的时间复杂度,因为erase操作也是$O(n)$的操作。 +这个代码看上去好像是O(n)的时间复杂度,其实是O(n^2)的时间复杂度,因为erase操作也是O(n)的操作。 所以此时使用双指针法才展现出效率的优势:**通过两个指针在一个for循环下完成两个for循环的工作。** @@ -30,7 +30,7 @@ for (int i = 0; i < array.size(); i++) { 在[字符串:这道题目,使用库函数一行代码搞定](https://programmercarl.com/0344.反转字符串.html)中讲解了反转字符串,注意这里强调要原地反转,要不然就失去了题目的意义。 -使用双指针法,**定义两个指针(也可以说是索引下标),一个从字符串前面,一个从字符串后面,两个指针同时向中间移动,并交换元素。**,时间复杂度是$O(n)$。 +使用双指针法,**定义两个指针(也可以说是索引下标),一个从字符串前面,一个从字符串后面,两个指针同时向中间移动,并交换元素。**,时间复杂度是O(n)。 在[替换空格](https://programmercarl.com/剑指Offer05.替换空格.html) 中介绍使用双指针填充字符串的方法,如果想把这道题目做到极致,就不要只用额外的辅助空间了! @@ -38,13 +38,13 @@ for (int i = 0; i < array.size(); i++) { 有同学问了,为什么要从后向前填充,从前向后填充不行么? -从前向后填充就是$O(n^2)$的算法了,因为每次添加元素都要将添加元素之后的所有元素向后移动。 +从前向后填充就是O(n^2)的算法了,因为每次添加元素都要将添加元素之后的所有元素向后移动。 **其实很多数组(字符串)填充类的问题,都可以先预先给数组扩容带填充后的大小,然后在从后向前进行操作。** -那么在[字符串:花式反转还不够!](https://programmercarl.com/0151.翻转字符串里的单词.html)中,我们使用双指针法,用$O(n)$的时间复杂度完成字符串删除类的操作,因为题目要产出冗余空格。 +那么在[字符串:花式反转还不够!](https://programmercarl.com/0151.翻转字符串里的单词.html)中,我们使用双指针法,用O(n)的时间复杂度完成字符串删除类的操作,因为题目要产出冗余空格。 -**在删除冗余空格的过程中,如果不注意代码效率,很容易写成了$O(n^2)$的时间复杂度。其实使用双指针法$O(n)$就可以搞定。** +**在删除冗余空格的过程中,如果不注意代码效率,很容易写成了O(n^2)的时间复杂度。其实使用双指针法O(n)就可以搞定。** **主要还是大家用erase用的比较随意,一定要注意for循环下用erase的情况,一般可以用双指针写效率更高!** @@ -74,15 +74,15 @@ for (int i = 0; i < array.size(); i++) { 去重的过程不好处理,有很多小细节,如果在面试中很难想到位。 -时间复杂度可以做到$O(n^2)$,但还是比较费时的,因为不好做剪枝操作。 +时间复杂度可以做到O(n^2),但还是比较费时的,因为不好做剪枝操作。 所以这道题目使用双指针法才是最为合适的,用双指针做这道题目才能就能真正体会到,**通过前后两个指针不算向中间逼近,在一个for循环下完成两个for循环的工作。** -只用双指针法时间复杂度为$O(n^2)$,但比哈希法的$O(n^2)$效率高得多,哈希法在使用两层for循环的时候,能做的剪枝操作很有限。 +只用双指针法时间复杂度为O(n^2),但比哈希法的O(n^2)效率高得多,哈希法在使用两层for循环的时候,能做的剪枝操作很有限。 在[双指针法:一样的道理,能解决四数之和](https://programmercarl.com/0018.四数之和.html)中,讲到了四数之和,其实思路是一样的,**在三数之和的基础上再套一层for循环,依然是使用双指针法。** -对于三数之和使用双指针法就是将原本暴力$O(n^3)$的解法,降为$O(n^2)$的解法,四数之和的双指针解法就是将原本暴力$O(n^4)$的解法,降为$O(n^3)$的解法。 +对于三数之和使用双指针法就是将原本暴力O(n^3)的解法,降为O(n^2)的解法,四数之和的双指针解法就是将原本暴力O(n^4)的解法,降为O(n^3)的解法。 同样的道理,五数之和,n数之和都是在这个基础上累加。 diff --git a/problems/回溯总结.md b/problems/回溯总结.md index bd0db575..5b8e2276 100644 --- a/problems/回溯总结.md +++ b/problems/回溯总结.md @@ -302,11 +302,11 @@ if (startIndex >= nums.size()) { // 终止条件可以不加 **而使用used数组在时间复杂度上几乎没有额外负担!** -**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是$O(n)$,但如果使用set去重,空间复杂度就变成了$O(n^2)$,因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 +**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是O(n),但如果使用set去重,空间复杂度就变成了$O(n^2)$,因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 -那有同学可能疑惑 用used数组也是占用$O(n)$的空间啊? +那有同学可能疑惑 用used数组也是占用O(n)的空间啊? -used数组可是全局变量,每层与每层之间公用一个used数组,所以空间复杂度是$O(n + n)$,最终空间复杂度还是$O(n)$。 +used数组可是全局变量,每层与每层之间公用一个used数组,所以空间复杂度是O(n + n),最终空间复杂度还是O(n)。 # 重新安排行程(图论额外拓展) @@ -380,8 +380,8 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所 以下在计算空间复杂度的时候我都把系统栈(不是数据结构里的栈)所占空间算进去。 子集问题分析: -* 时间复杂度:O(2^n),因为每一个元素的状态无外乎取与不取,所以时间复杂度为$O(2^n)$ -* 空间复杂度:O(n),递归深度为n,所以系统栈所用空间为$O(n)$,每一层递归所用的空间都是常数级别,注意代码里的result和path都是全局变量,就算是放在参数里,传的也是引用,并不会新申请内存空间,最终空间复杂度为$O(n)$ +* 时间复杂度:O(2^n),因为每一个元素的状态无外乎取与不取,所以时间复杂度为O(2^n) +* 空间复杂度:O(n),递归深度为n,所以系统栈所用空间为O(n),每一层递归所用的空间都是常数级别,注意代码里的result和path都是全局变量,就算是放在参数里,传的也是引用,并不会新申请内存空间,最终空间复杂度为O(n) 排列问题分析: * 时间复杂度:O(n!),这个可以从排列的树形图中很明显发现,每一层节点为n,第二层每一个分支都延伸了n-1个分支,再往下又是n-2个分支,所以一直到叶子节点一共就是 n * n-1 * n-2 * ..... 1 = n!。 @@ -392,7 +392,7 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所 * 空间复杂度:O(n),和子集问题同理。 N皇后问题分析: -* 时间复杂度:O(n!) ,其实如果看树形图的话,直觉上是$O(n^n)$,但皇后之间不能见面所以在搜索的过程中是有剪枝的,最差也就是O(n!),n!表示n * (n-1) * .... * 1。 +* 时间复杂度:O(n!) ,其实如果看树形图的话,直觉上是O(n^n),但皇后之间不能见面所以在搜索的过程中是有剪枝的,最差也就是O(n!),n!表示n * (n-1) * .... * 1。 * 空间复杂度:O(n),和子集问题同理。 解数独问题分析: diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index 7a601493..b4bdda00 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -226,11 +226,11 @@ public: **而使用used数组在时间复杂度上几乎没有额外负担!** -**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是$O(n)$,但如果使用set去重,空间复杂度就变成了$O(n^2)$,因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 +**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是O(n),但如果使用set去重,空间复杂度就变成了O(n^2),因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 -那有同学可能疑惑 用used数组也是占用$O(n)$的空间啊? +那有同学可能疑惑 用used数组也是占用O(n)的空间啊? -used数组可是全局变量,每层与每层之间公用一个used数组,所以空间复杂度是$O(n + n)$,最终空间复杂度还是$O(n)$。 +used数组可是全局变量,每层与每层之间公用一个used数组,所以空间复杂度是O(n + n),最终空间复杂度还是O(n)。 ## 总结 diff --git a/problems/字符串总结.md b/problems/字符串总结.md index 469cb743..1993b44b 100644 --- a/problems/字符串总结.md +++ b/problems/字符串总结.md @@ -57,15 +57,15 @@ for (int i = 0; i < a.size(); i++) { 在[344.反转字符串](https://programmercarl.com/0344.反转字符串.html) ,我们使用双指针法实现了反转字符串的操作,**双指针法在数组,链表和字符串中很常用。** -接着在[字符串:替换空格](https://programmercarl.com/剑指Offer05.替换空格.html),同样还是使用双指针法在时间复杂度$O(n)$的情况下完成替换空格。 +接着在[字符串:替换空格](https://programmercarl.com/剑指Offer05.替换空格.html),同样还是使用双指针法在时间复杂度O(n)的情况下完成替换空格。 **其实很多数组填充类的问题,都可以先预先给数组扩容带填充后的大小,然后在从后向前进行操作。** 那么针对数组删除操作的问题,其实在[27. 移除元素](https://programmercarl.com/0027.移除元素.html)中就已经提到了使用双指针法进行移除操作。 -同样的道理在[151.翻转字符串里的单词](https://programmercarl.com/0151.翻转字符串里的单词.html)中我们使用$O(n)$的时间复杂度,完成了删除冗余空格。 +同样的道理在[151.翻转字符串里的单词](https://programmercarl.com/0151.翻转字符串里的单词.html)中我们使用O(n)的时间复杂度,完成了删除冗余空格。 -一些同学会使用for循环里调用库函数erase来移除元素,这其实是$O(n^2)$的操作,因为erase就是$O(n)$的操作,所以这也是典型的不知道库函数的时间复杂度,上来就用的案例了。 +一些同学会使用for循环里调用库函数erase来移除元素,这其实是O(n^2)的操作,因为erase就是O(n)的操作,所以这也是典型的不知道库函数的时间复杂度,上来就用的案例了。 # 反转系列 diff --git a/problems/数组总结篇.md b/problems/数组总结篇.md index d3d4a1e2..242c1498 100644 --- a/problems/数组总结篇.md +++ b/problems/数组总结篇.md @@ -67,8 +67,8 @@ 可以使用暴力解法,通过这道题目,如果追求更优的算法,建议试一试用二分法,来解决这道题目 -* 暴力解法时间复杂度:$O(n)$ -* 二分法时间复杂度:$O(\log n)$ +* 暴力解法时间复杂度:O(n) +* 二分法时间复杂度:O(logn) 在这道题目中我们讲到了**循环不变量原则**,只有在循环中坚持对区间的定义,才能清楚的把握循环中的各种细节。 @@ -81,8 +81,8 @@ 双指针法(快慢指针法):**通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。** -* 暴力解法时间复杂度:$O(n^2)$ -* 双指针时间复杂度:$O(n)$ +* 暴力解法时间复杂度:O(n^2) +* 双指针时间复杂度:O(n) 这道题目迷惑了不少同学,纠结于数组中的元素为什么不能删除,主要是因为以下两点: @@ -97,8 +97,8 @@ 本题介绍了数组操作中的另一个重要思想:滑动窗口。 -* 暴力解法时间复杂度:$O(n^2)$ -* 滑动窗口时间复杂度:$O(n)$ +* 暴力解法时间复杂度:O(n^2) +* 滑动窗口时间复杂度:O(n) 本题中,主要要理解滑动窗口如何移动 窗口起始位置,达到动态更新窗口大小的,从而得出长度最小的符合条件的长度。 diff --git a/problems/根据身高重建队列(vector原理讲解).md b/problems/根据身高重建队列(vector原理讲解).md index 11a72e2d..6d248c40 100644 --- a/problems/根据身高重建队列(vector原理讲解).md +++ b/problems/根据身高重建队列(vector原理讲解).md @@ -33,7 +33,7 @@ public: 耗时如下: ![vectorinsert](https://img-blog.csdnimg.cn/20201218203611181.png) -其直观上来看数组的insert操作是$O(n)$的,整体代码的时间复杂度是$O(n^2)$。 +其直观上来看数组的insert操作是O(n)的,整体代码的时间复杂度是O(n^2)。 这么一分析好像和版本二链表实现的时间复杂度是一样的啊,为什么提交之后效率会差距这么大呢? ```CPP @@ -97,7 +97,7 @@ for (int i = 0; i < vec.size(); i++) { **同时也注意此时capicity和size的变化,关键的地方我都标红了**。 -而在[贪心算法:根据身高重建队列](https://programmercarl.com/0406.根据身高重建队列.html)中,我们使用vector来做insert的操作,此时大家可会发现,**虽然表面上复杂度是$O(n^2)$,但是其底层都不知道额外做了多少次全量拷贝了,所以算上vector的底层拷贝,整体时间复杂度可以认为是$O(n^2 + t × n)$级别的,t是底层拷贝的次数**。 +而在[贪心算法:根据身高重建队列](https://programmercarl.com/0406.根据身高重建队列.html)中,我们使用vector来做insert的操作,此时大家可会发现,**虽然表面上复杂度是O(n^2),但是其底层都不知道额外做了多少次全量拷贝了,所以算上vector的底层拷贝,整体时间复杂度可以认为是O(n^2 + t × n)级别的,t是底层拷贝的次数**。 那么是不是可以直接确定好vector的大小,不让它在动态扩容了,例如在[贪心算法:根据身高重建队列](https://programmercarl.com/0406.根据身高重建队列.html)中已经给出了有people.size这么多的人,可以定义好一个固定大小的vector,这样我们就可以控制vector,不让它底层动态扩容。 @@ -133,7 +133,7 @@ public: ![vector手动模拟insert](https://img-blog.csdnimg.cn/20201218200626718.png) -这份代码就是不让vector动态扩容,全程我们自己模拟insert的操作,大家也可以直观的看出是一个$O(n^2)$的方法了。 +这份代码就是不让vector动态扩容,全程我们自己模拟insert的操作,大家也可以直观的看出是一个O(n^2)的方法了。 但这份代码在leetcode上统计的耗时甚至比版本一的还高,我们都不让它动态扩容了,为什么耗时更高了呢? @@ -151,7 +151,7 @@ public: 大家应该发现了,编程语言中一个普通容器的insert,delete的使用,都可能对写出来的算法的有很大影响! -如果抛开语言谈算法,除非从来不用代码写算法纯分析,**否则的话,语言功底不到位$O(n)$的算法可以写出$O(n^2)$的性能**,哈哈。 +如果抛开语言谈算法,除非从来不用代码写算法纯分析,**否则的话,语言功底不到位O(n)的算法可以写出$O(n^2)$的性能**,哈哈。 相信在这里学习算法的录友们,都是想在软件行业长远发展的,都是要从事编程的工作,那么一定要深耕好一门编程语言,这个非常重要! diff --git a/problems/知识星球精选/刷力扣用不用库函数.md b/problems/知识星球精选/刷力扣用不用库函数.md index b52e4d03..c8e2f5c6 100644 --- a/problems/知识星球精选/刷力扣用不用库函数.md +++ b/problems/知识星球精选/刷力扣用不用库函数.md @@ -27,7 +27,7 @@ 使用库函数最大的忌讳就是不知道这个库函数怎么实现的,也不知道其时间复杂度,上来就用,这样写出来的算法,时间复杂度自己都掌握不好的。 -例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是$O(n^2)$的时间复杂度了。 +例如for循环里套一个字符串的insert,erase之类的操作,你说时间复杂度是多少呢,很明显是O(n^2)的时间复杂度了。 在刷题的时候本着我说的标准来使用库函数,详细对大家回有所帮助! diff --git a/problems/背包问题理论基础多重背包.md b/problems/背包问题理论基础多重背包.md index d05c3445..a988db2c 100644 --- a/problems/背包问题理论基础多重背包.md +++ b/problems/背包问题理论基础多重背包.md @@ -89,7 +89,7 @@ int main() { ``` -* 时间复杂度:$O(m × n × k)$,m:物品种类个数,n背包容量,k单类物品数量 +* 时间复杂度:O(m × n × k),m:物品种类个数,n背包容量,k单类物品数量 也有另一种实现方式,就是把每种商品遍历的个数放在01背包里面在遍历一遍。 @@ -125,7 +125,7 @@ int main() { } ``` -* 时间复杂度:$O(m × n × k)$,m:物品种类个数,n背包容量,k单类物品数量 +* 时间复杂度:O(m × n × k),m:物品种类个数,n背包容量,k单类物品数量 从代码里可以看出是01背包里面在加一个for循环遍历一个每种商品的数量。 和01背包还是如出一辙的。 diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index a4fefa2b..095282f5 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -120,9 +120,9 @@ head->val = 5; ![链表-添加节点](https://img-blog.csdnimg.cn/20200806195134331.png) -可以看出链表的增添和删除都是$O(1)$操作,也不会影响到其他节点。 +可以看出链表的增添和删除都是O(1)操作,也不会影响到其他节点。 -但是要注意,要是删除第五个节点,需要从头节点查找到第四个节点通过next指针进行删除操作,查找的时间复杂度是$O(n)$。 +但是要注意,要是删除第五个节点,需要从头节点查找到第四个节点通过next指针进行删除操作,查找的时间复杂度是O(n)。 # 性能分析 From d1ea59aebd4659274165c5a352166696275faddc Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 31 Mar 2022 22:14:20 +0800 Subject: [PATCH 236/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880093.?= =?UTF-8?q?=E5=A4=8D=E5=8E=9FIP=E5=9C=B0=E5=9D=80.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 714dcb4f..7910fc50 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -455,6 +455,45 @@ var restoreIpAddresses = function(s) { }; ``` +## TypeScript + +```typescript +function isValidIpSegment(str: string): boolean { + let resBool: boolean = true; + let tempVal: number = Number(str); + if ( + str.length === 0 || isNaN(tempVal) || + tempVal > 255 || tempVal < 0 || + (str.length > 1 && str[0] === '0') + ) { + resBool = false; + } + return resBool; +} +function restoreIpAddresses(s: string): string[] { + const resArr: string[] = []; + backTracking(s, 0, []); + return resArr; + function backTracking(s: string, startIndex: number, route: string[]): void { + let length: number = s.length; + if (route.length === 4 && startIndex >= length) { + resArr.push(route.join('.')); + return; + } + if (route.length === 4 || startIndex >= length) return; + let tempStr: string = ''; + for (let i = startIndex + 1; i <= Math.min(length, startIndex + 3); i++) { + tempStr = s.slice(startIndex, i); + if (isValidIpSegment(tempStr)) { + route.push(s.slice(startIndex, i)); + backTracking(s, i, route); + route.pop(); + } + } + } +}; +``` + ## Go 回溯(对于前导 0的IP(特别注意s[startIndex]=='0'的判断,不应该写成s[startIndex]==0,因为s截取出来不是数字)) From 48de0f8bd55e24b2b9233648e0f85e4fcb75c0c0 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 1 Apr 2022 11:02:47 +0800 Subject: [PATCH 237/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880078.?= =?UTF-8?q?=E5=AD=90=E9=9B=86.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0078.子集.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0078.子集.md b/problems/0078.子集.md index cdb5f548..e1c52b5b 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -272,7 +272,28 @@ var subsets = function(nums) { }; ``` +## TypeScript + +```typescript +function subsets(nums: number[]): number[][] { + const resArr: number[][] = []; + backTracking(nums, 0, []); + return resArr; + function backTracking(nums: number[], startIndex: number, route: number[]): void { + resArr.push(route.slice()); + let length = nums.length; + if (startIndex === length) return; + for (let i = startIndex; i < length; i++) { + route.push(nums[i]); + backTracking(nums, i + 1, route); + route.pop(); + } + } +}; +``` + ## C + ```c int* path; int pathTop; From b85700890227fa69a7ca506384e7e8a821530675 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 1 Apr 2022 12:08:26 +0800 Subject: [PATCH 238/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880090.?= =?UTF-8?q?=E5=AD=90=E9=9B=86II.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0type?= =?UTF-8?q?script=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 16bd1f2c..6469f4ba 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -319,6 +319,28 @@ var subsetsWithDup = function(nums) { ``` +### TypeScript + +```typescript +function subsetsWithDup(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const resArr: number[][] = []; + backTraking(nums, 0, []); + return resArr; + function backTraking(nums: number[], startIndex: number, route: number[]): void { + resArr.push(route.slice()); + let length: number = nums.length; + if (startIndex === length) return; + for (let i = startIndex; i < length; i++) { + if (i > startIndex && nums[i] === nums[i - 1]) continue; + route.push(nums[i]); + backTraking(nums, i + 1, route); + route.pop(); + } + } +}; +``` + ### C ```c @@ -388,7 +410,7 @@ int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** returnColum } ``` -## Swift +### Swift ```swift func subsetsWithDup(_ nums: [Int]) -> [[Int]] { From c4a4a0323127f3b47e89fdeefd7bc8a57d404e1e Mon Sep 17 00:00:00 2001 From: Effy Wang Date: Fri, 1 Apr 2022 17:26:47 +0800 Subject: [PATCH 239/257] =?UTF-8?q?Update=200704.=E4=BA=8C=E5=88=86?= =?UTF-8?q?=E6=9F=A5=E6=89=BE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add detailed comments to the Javascript version of Binary Search --- problems/0704.二分查找.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 15e096a0..55625130 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -276,7 +276,7 @@ func search(nums []int, target int) int { ``` **JavaScript:** -(版本一)左闭右闭区间 +(版本一)左闭右闭区间 [left, right] ```js /** @@ -285,10 +285,12 @@ func search(nums []int, target int) int { * @return {number} */ var search = function(nums, target) { + // right是数组最后一个数的下标,num[right]在查找范围内,是左闭右闭区间 let left = 0, right = nums.length - 1; - // 使用左闭右闭区间 + // 当left=right时,由于nums[right]在查找范围内,所以要包括此情况 while (left <= right) { let mid = left + Math.floor((right - left)/2); + // 如果中间数大于目标值,要把中间数排除查找范围,所以右边界更新为mid-1;如果右边界更新为mid,那中间数还在下次查找范围内 if (nums[mid] > target) { right = mid - 1; // 去左面闭区间寻找 } else if (nums[mid] < target) { @@ -300,7 +302,7 @@ var search = function(nums, target) { return -1; }; ``` -(版本二)左闭右开区间 +(版本二)左闭右开区间 [left, right) ```js /** @@ -309,10 +311,13 @@ var search = function(nums, target) { * @return {number} */ var search = function(nums, target) { - let left = 0, right = nums.length; - // 使用左闭右开区间 [left, right) + // right是数组最后一个数的下标+1,nums[right]不在查找范围内,是左闭右开区间 + let left = 0, right = nums.length; + // 当left=right时,由于nums[right]不在查找范围,所以不必包括此情况 while (left < right) { let mid = left + Math.floor((right - left)/2); + // 如果中间值大于目标值,中间值不应在下次查找的范围内,但中间值的前一个值应在; + // 由于right本来就不在查找范围内,所以将右边界更新为中间值,如果更新右边界为mid-1则将中间值的前一个值也踢出了下次寻找范围 if (nums[mid] > target) { right = mid; // 去左区间寻找 } else if (nums[mid] < target) { From 3f7dd67a8031663d2b673a41587e3a640e0a4b1f Mon Sep 17 00:00:00 2001 From: FrankLin Date: Fri, 1 Apr 2022 10:57:25 -0400 Subject: [PATCH 240/257] Add C version for LeetCode349 using array --- problems/0349.两个数组的交集.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 82be1829..64d80a37 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -281,6 +281,38 @@ impl Solution { } } ``` + +C: +```C +int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){ + + int nums1Cnt[1000] = {0}; + int lessSize = nums1Size < nums2Size ? nums1Size : nums2Size; + int * result = (int *) calloc(lessSize, sizeof(int)); + int resultIndex = 0; + int* tempNums; + + int i; + + //Calculate the number's counts for nums1 array + for(i = 0; i < nums1Size; i ++) { + nums1Cnt[nums1[i]]++; + } + + //Check if the value existing in nums1 count array + for(i = 0; i < nums2Size; i ++) { + if(nums1Cnt[nums2[i]] > 0) { + result[resultIndex] = nums2[i]; + resultIndex ++; + //Clear this count to avoid duplicated value + nums1Cnt[nums2[i]] = 0; + } + } + * returnSize = resultIndex; + return result; +} +``` + ## 相关题目 * 350.两个数组的交集 II From abc08b6bb6f698135efe52ad0a7f20b333d32173 Mon Sep 17 00:00:00 2001 From: FrankLin Date: Fri, 1 Apr 2022 11:01:00 -0400 Subject: [PATCH 241/257] correct comments of C version of Leetcode349 --- problems/0349.两个数组的交集.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 64d80a37..45f19b6e 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -294,17 +294,17 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re int i; - //Calculate the number's counts for nums1 array + /* Calculate the number's counts for nums1 array */ for(i = 0; i < nums1Size; i ++) { nums1Cnt[nums1[i]]++; } - //Check if the value existing in nums1 count array + /* Check if the value in nums2 is existing in nums1 count array */ for(i = 0; i < nums2Size; i ++) { if(nums1Cnt[nums2[i]] > 0) { result[resultIndex] = nums2[i]; resultIndex ++; - //Clear this count to avoid duplicated value + /* Clear this count to avoid duplicated value */ nums1Cnt[nums2[i]] = 0; } } From 297a22fd880f207bd9b621b7dbd5e8dfd84340a1 Mon Sep 17 00:00:00 2001 From: FrankLin Date: Fri, 1 Apr 2022 15:11:00 -0400 Subject: [PATCH 242/257] Add C version for Leetcode202 passed Leetcode submission --- problems/0202.快乐数.md | 70 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index f0a46a40..741a735a 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -315,5 +315,75 @@ class Solution { } ``` +C: +```C +typedef struct HashNodeTag { + int key; /* num */ + struct HashNodeTag *next; +}HashNode; + +/* Calcualte the hash key */ +static inline int hash(int key, int size) { + int index = key % size; + return (index > 0) ? (index) : (-index); +} + +/* Calculate the sum of the squares of its digits*/ +static inline int calcSquareSum(int num) { + unsigned int sum = 0; + while(num > 0) { + sum += (num % 10) * (num % 10); + num = num/10; + } + return sum; +} + +#define HASH_TABLE_SIZE (32) + +bool isHappy(int n){ + int sum = n; + int index = 0; + bool bHappy = false; + bool bExit = false; + /* allocate the memory for hash table with chaining method*/ + HashNode ** hashTable = (HashNode **)calloc(HASH_TABLE_SIZE, sizeof(HashNode)); + + while(bExit == false) { + /* check if n has been calculated */ + index = hash(n, HASH_TABLE_SIZE); + + HashNode ** p = hashTable + index; + + while((*p) && (bExit == false)) { + /* Check if this num was calculated, if yes, this will be endless loop */ + if((*p)->key == n) { + bHappy = false; + bExit = true; + } + /* move to next node of the same index */ + p = &((*p)->next); + } + + /* put n intot hash table */ + HashNode * newNode = (HashNode *)malloc(sizeof(HashNode)); + newNode->key = n; + newNode->next = NULL; + + *p = newNode; + + sum = calcSquareSum(n); + if(sum == 1) { + bHappy = true; + bExit = true; + } + else { + n = sum; + + } + } + + return bHappy; +} +``` -----------------------
From fb5571f16576d9d16274219d60674662970366ec Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 2 Apr 2022 11:24:06 +0800 Subject: [PATCH 243/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880491.?= =?UTF-8?q?=E9=80=92=E5=A2=9E=E5=AD=90=E5=BA=8F=E5=88=97.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/0491.递增子序列.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 6103c3d0..3ea2382b 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -396,7 +396,35 @@ var findSubsequences = function(nums) { ``` +## TypeScript + +```typescript +function findSubsequences(nums: number[]): number[][] { + const resArr: number[][] = []; + backTracking(nums, 0, []); + return resArr; + function backTracking(nums: number[], startIndex: number, route: number[]): void { + let length: number = nums.length; + if (route.length >= 2) { + resArr.push(route.slice()); + } + const usedSet: Set = new Set(); + for (let i = startIndex; i < length; i++) { + if ( + nums[i] < route[route.length - 1] || + usedSet.has(nums[i]) + ) continue; + usedSet.add(nums[i]); + route.push(nums[i]); + backTracking(nums, i + 1, route); + route.pop(); + } + } +}; +``` + ### C + ```c int* path; int pathTop; From 9b9a37b92c20fc616b7808317ba05ff03c6d8633 Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Sat, 2 Apr 2022 00:03:08 -0500 Subject: [PATCH 244/257] 0455 typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0455思路多打了一个“了” --- problems/0455.分发饼干.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 210b492d..5c86e478 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -32,7 +32,7 @@ ## 思路 -为了了满足更多的小孩,就不要造成饼干尺寸的浪费。 +为了满足更多的小孩,就不要造成饼干尺寸的浪费。 大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的。 From 77f1e2c85da13846b26cd33159e0dee565ef1d9d Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 2 Apr 2022 19:24:03 +0800 Subject: [PATCH 245/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880046.?= =?UTF-8?q?=E5=85=A8=E6=8E=92=E5=88=97.md=EF=BC=89=EF=BC=9A=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0typesript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index c5369ddd..836c3646 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -331,6 +331,34 @@ var permute = function(nums) { ``` +## TypeScript + +```typescript +function permute(nums: number[]): number[][] { + const resArr: number[][] = []; + const helperSet: Set = new Set(); + backTracking(nums, []); + return resArr; + function backTracking(nums: number[], route: number[]): void { + if (route.length === nums.length) { + resArr.push(route.slice()); + return; + } + let tempVal: number; + for (let i = 0, length = nums.length; i < length; i++) { + tempVal = nums[i]; + if (!helperSet.has(tempVal)) { + route.push(tempVal); + helperSet.add(tempVal); + backTracking(nums, route); + route.pop(); + helperSet.delete(tempVal); + } + } + } +}; +``` + ### C ```c From c9dfda1c955c0665108d8aa7fc78b33d5edded99 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 2 Apr 2022 23:34:25 +0800 Subject: [PATCH 246/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880047.?= =?UTF-8?q?=E5=85=A8=E6=8E=92=E5=88=97II.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/0047.全排列II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index 0cecac50..cce25cd9 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -292,6 +292,34 @@ var permuteUnique = function (nums) { ``` +### TypeScript + +```typescript +function permuteUnique(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const resArr: number[][] = []; + const usedArr: boolean[] = new Array(nums.length).fill(false); + backTracking(nums, []); + return resArr; + function backTracking(nums: number[], route: number[]): void { + if (route.length === nums.length) { + resArr.push(route.slice()); + return; + } + for (let i = 0, length = nums.length; i < length; i++) { + if (i > 0 && nums[i] === nums[i - 1] && usedArr[i - 1] === false) continue; + if (usedArr[i] === false) { + route.push(nums[i]); + usedArr[i] = true; + backTracking(nums, route); + usedArr[i] = false; + route.pop(); + } + } + } +}; +``` + ### Swift ```swift From 710e816012bb0198a5a42686e94d24b50aa68760 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 3 Apr 2022 11:26:52 +0800 Subject: [PATCH 247/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=EF=BC=8820201112?= =?UTF-8?q?=E5=9B=9E=E6=BA=AF=E5=91=A8=E6=9C=AB=E6=80=BB=E7=BB=93.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E8=A1=A5=E5=85=85=E5=88=86=E6=9E=90=E6=8E=92?= =?UTF-8?q?=E5=88=97=E9=97=AE=E9=A2=98=E6=97=B6=E9=97=B4=E5=A4=8D=E6=9D=82?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/周总结/20201112回溯周末总结.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/周总结/20201112回溯周末总结.md b/problems/周总结/20201112回溯周末总结.md index c61de4bb..af08097b 100644 --- a/problems/周总结/20201112回溯周末总结.md +++ b/problems/周总结/20201112回溯周末总结.md @@ -76,7 +76,7 @@ * 空间复杂度:$O(n)$,递归深度为n,所以系统栈所用空间为$O(n)$,每一层递归所用的空间都是常数级别,注意代码里的result和path都是全局变量,就算是放在参数里,传的也是引用,并不会新申请内存空间,最终空间复杂度为$O(n)$。 排列问题分析: -* 时间复杂度:$O(n!)$,这个可以从排列的树形图中很明显发现,每一层节点为n,第二层每一个分支都延伸了n-1个分支,再往下又是n-2个分支,所以一直到叶子节点一共就是 n * n-1 * n-2 * ..... 1 = n!。 +* 时间复杂度:$O(n!)$,这个可以从排列的树形图中很明显发现,每一层节点为n,第二层每一个分支都延伸了n-1个分支,再往下又是n-2个分支,所以一直到叶子节点一共就是 n * n-1 * n-2 * ..... 1 = n!。每个叶子节点都会有一个构造全排列填进数组的操作(对应的代码:`result.push_back(path)`),该操作的复杂度为$O(n)$。所以,最终时间复杂度为:n * n!,简化为$O(n!)$。 * 空间复杂度:$O(n)$,和子集问题同理。 组合问题分析: From e48336238d25eac775f1897ad85b9be551ba1e69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=A2=A6=E6=B4=81?= <3224935686@qq.com> Date: Sun, 3 Apr 2022 14:03:31 +0800 Subject: [PATCH 248/257] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=B3=BB=E5=88=9719=20=E4=BB=8E=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91JS=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8F=98=E9=87=8F=E5=90=8D=20preorder->inorder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0106.从中序与后序遍历序列构造二叉树.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 496de431..7ecca773 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -790,7 +790,7 @@ func findRootIndex(target int,inorder []int) int{ ```javascript var buildTree = function(inorder, postorder) { - if (!preorder.length) return null; + if (!inorder.length) return null; const rootVal = postorder.pop(); // 从后序遍历的数组中获取中间节点的值, 即数组最后一个值 let rootIndex = inorder.indexOf(rootVal); // 获取中间节点在中序遍历中的下标 const root = new TreeNode(rootVal); // 创建中间节点 From 1dcbf7f6f0ba7b50da6685532a42d2ceac9aeccc Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 3 Apr 2022 19:43:34 +0800 Subject: [PATCH 249/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E5=9B=9E?= =?UTF-8?q?=E6=BA=AF=E7=AE=97=E6=B3=95=E5=8E=BB=E9=87=8D=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E7=9A=84=E5=8F=A6=E4=B8=80=E7=A7=8D=E5=86=99=E6=B3=95.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/回溯算法去重问题的另一种写法.md | 81 ++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index b4bdda00..f48097e1 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -365,6 +365,87 @@ class Solution: return res ``` +TypeScript: + +**90.子集II** + +```typescript +function subsetsWithDup(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const resArr: number[][] = []; + backTraking(nums, 0, []); + return resArr; + function backTraking(nums: number[], startIndex: number, route: number[]): void { + resArr.push(route.slice()); + const helperSet: Set = new Set(); + for (let i = startIndex, length = nums.length; i < length; i++) { + if (helperSet.has(nums[i])) continue; + helperSet.add(nums[i]); + route.push(nums[i]); + backTraking(nums, i + 1, route); + route.pop(); + } + } +}; +``` + +**40. 组合总和 II** + +```typescript +function combinationSum2(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const resArr: number[][] = []; + backTracking(candidates, target, 0, 0, []); + return resArr; + function backTracking( + candidates: number[], target: number, + curSum: number, startIndex: number, route: number[] + ) { + if (curSum > target) return; + if (curSum === target) { + resArr.push(route.slice()); + return; + } + const helperSet: Set = new Set(); + for (let i = startIndex, length = candidates.length; i < length; i++) { + let tempVal: number = candidates[i]; + if (helperSet.has(tempVal)) continue; + helperSet.add(tempVal); + route.push(tempVal); + backTracking(candidates, target, curSum + tempVal, i + 1, route); + route.pop(); + + } + } +}; +``` + +**47. 全排列 II** + +```typescript +function permuteUnique(nums: number[]): number[][] { + const resArr: number[][] = []; + const usedArr: boolean[] = []; + backTracking(nums, []); + return resArr; + function backTracking(nums: number[], route: number[]): void { + if (nums.length === route.length) { + resArr.push(route.slice()); + return; + } + const usedSet: Set = new Set(); + for (let i = 0, length = nums.length; i < length; i++) { + if (usedArr[i] === true || usedSet.has(nums[i])) continue; + usedSet.add(nums[i]); + route.push(nums[i]); + usedArr[i] = true; + backTracking(nums, route); + usedArr[i] = false; + route.pop(); + } + } +}; +``` Go: From 3635751759fcf689f9baae10ab5fe4a5d642b5f8 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 3 Apr 2022 23:15:06 +0800 Subject: [PATCH 250/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880332.?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E5=AE=89=E6=8E=92=E8=A1=8C=E7=A8=8B.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0332.重新安排行程.md | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 01f81c4d..370db45b 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -448,6 +448,50 @@ var findItinerary = function(tickets) { ``` +### TypeScript + +```typescript +function findItinerary(tickets: string[][]): string[] { + /** + TicketsMap 实例: + { NRT: Map(1) { 'JFK' => 1 }, JFK: Map(2) { 'KUL' => 1, 'NRT' => 1 } } + 这里选择Map数据结构的原因是:与Object类型的一个主要差异是,Map实例会维护键值对的插入顺序。 + */ + type TicketsMap = { + [index: string]: Map + }; + tickets.sort((a, b) => { + return a[1] < b[1] ? -1 : 1; + }); + const ticketMap: TicketsMap = {}; + for (const [from, to] of tickets) { + if (ticketMap[from] === undefined) { + ticketMap[from] = new Map(); + } + ticketMap[from].set(to, (ticketMap[from].get(to) || 0) + 1); + } + const resRoute = ['JFK']; + backTracking(tickets.length, ticketMap, resRoute); + return resRoute; + function backTracking(ticketNum: number, ticketMap: TicketsMap, route: string[]): boolean { + if (route.length === ticketNum + 1) return true; + const targetMap = ticketMap[route[route.length - 1]]; + if (targetMap !== undefined) { + for (const [to, count] of targetMap.entries()) { + if (count > 0) { + route.push(to); + targetMap.set(to, count - 1); + if (backTracking(ticketNum, ticketMap, route) === true) return true; + targetMap.set(to, count); + route.pop(); + } + } + } + return false; + } +}; +``` + ### Swift 直接迭代tickets数组: From 69a9316bebce0fc3f43835bb9245f124076f105f Mon Sep 17 00:00:00 2001 From: SianXiaoCHN Date: Sun, 3 Apr 2022 23:42:04 -0500 Subject: [PATCH 251/257] =?UTF-8?q?python=200860.=E6=9F=A0=E6=AA=AC?= =?UTF-8?q?=E6=B0=B4=E6=89=BE=E9=9B=B6=20=E5=8E=BB=E9=99=A4=E6=97=A0?= =?UTF-8?q?=E7=94=A8=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python 0860.柠檬水找零 去除无用变量:在本题中,20的数量是无用的,因为不需要用来找零,可以不用维护这个变量。 --- problems/0860.柠檬水找零.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index f48ecf4d..ffd5490d 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -157,7 +157,7 @@ class Solution { ```python class Solution: def lemonadeChange(self, bills: List[int]) -> bool: - five, ten, twenty = 0, 0, 0 + five, ten = 0, 0 for bill in bills: if bill == 5: five += 1 @@ -169,10 +169,8 @@ class Solution: if ten > 0 and five > 0: ten -= 1 five -= 1 - twenty += 1 elif five > 2: five -= 3 - twenty += 1 else: return False return True From d3a69ff358793c6c4f6f7636935b545437404f21 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Mon, 4 Apr 2022 12:55:12 +0800 Subject: [PATCH 252/257] Add one more python code --- problems/0098.验证二叉搜索树.md | 23 +++++++++++++++++++++- problems/0101.对称二叉树.md | 35 --------------------------------- 2 files changed, 22 insertions(+), 36 deletions(-) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 4ed29619..ff4335fc 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -408,7 +408,28 @@ class Solution: return True ``` -## Go +```python +# 遵循Carl的写法,只添加了节点判断的部分 +class Solution: + def isValidBST(self, root: TreeNode) -> bool: + # method 2 + que, pre = [], None + while root or que: + while root: + que.append(root) + root = root.left + root = que.pop() + # 对第一个节点只做记录,对后面的节点进行比较 + if pre is None: + pre = root.val + else: + if pre >= root.val: return False + pre = root.val + root = root.right + return True +``` + +## Go ```Go import "math" diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 0007b4d4..e4e232c8 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -437,41 +437,6 @@ class Solution: return True ``` -层序遍历 - -```python -class Solution: - def isSymmetric(self, root: TreeNode) -> bool: - if not root: return True - que, cnt = [[root.left, root.right]], 1 - while que: - nodes, tmp, sign = que.pop(), [], False - for node in nodes: - if not node: - tmp.append(None) - tmp.append(None) - else: - if node.left: - tmp.append(node.left) - sign = True - else: - tmp.append(None) - if node.right: - tmp.append(node.right) - sign = True - else: - tmp.append(None) - p1, p2 = 0, len(nodes) - 1 - while p1 < p2: - if (not nodes[p1] and nodes[p2]) or (nodes[p1] and not nodes[p2]): return False - elif nodes[p1] and nodes[p2] and nodes[p1].val != nodes[p2].val: return False - p1 += 1 - p2 -= 1 - if sign: que.append(tmp) - cnt += 1 - return True -``` - ## Go ```go From 2b80a6d36af3c00b260b55395361a8c960a02d0a Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 4 Apr 2022 16:56:36 +0800 Subject: [PATCH 253/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880051.N?= =?UTF-8?q?=E7=9A=87=E5=90=8E.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0051.N皇后.md | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 7eb0d7a0..85524e6f 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -457,6 +457,58 @@ var solveNQueens = function(n) { }; ``` +## TypeScript + +```typescript +function solveNQueens(n: number): string[][] { + const board: string[][] = new Array(n).fill(0).map(_ => new Array(n).fill('.')); + const resArr: string[][] = []; + backTracking(n, 0, board); + return resArr; + function backTracking(n: number, rowNum: number, board: string[][]): void { + if (rowNum === n) { + resArr.push(transformBoard(board)); + return; + } + for (let i = 0; i < n; i++) { + if (isValid(i, rowNum, board) === true) { + board[rowNum][i] = 'Q'; + backTracking(n, rowNum + 1, board); + board[rowNum][i] = '.'; + } + } + } +}; +function isValid(col: number, row: number, board: string[][]): boolean { + const n: number = board.length; + if (col < 0 || col >= n || row < 0 || row >= n) return false; + // 检查列 + for (let row of board) { + if (row[col] === 'Q') return false; + } + // 检查45度方向 + let x: number = col, + y: number = row; + while (y >= 0 && x < n) { + if (board[y--][x++] === 'Q') return false; + } + // 检查135度方向 + x = col; + y = row; + while (x >= 0 && y >= 0) { + if (board[y--][x--] === 'Q') return false; + } + return true; +} +function transformBoard(board: string[][]): string[] { + const resArr = []; + for (let row of board) { + resArr.push(row.join('')); + } + return resArr; +} +``` + ### Swift ```swift From c590dfc5f29e910a85798f144bcc7178dda2bde4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Thu, 7 Apr 2022 09:34:25 +0800 Subject: [PATCH 254/257] Delete yarn.lock --- yarn.lock | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 yarn.lock diff --git a/yarn.lock b/yarn.lock deleted file mode 100644 index 3ff608ae..00000000 --- a/yarn.lock +++ /dev/null @@ -1,4 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - From bbe312015eca5207064aa42f3530e254845a1e62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98Carl?= Date: Thu, 7 Apr 2022 09:34:51 +0800 Subject: [PATCH 255/257] Delete .yarn-integrity --- node_modules/.yarn-integrity | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 node_modules/.yarn-integrity diff --git a/node_modules/.yarn-integrity b/node_modules/.yarn-integrity deleted file mode 100644 index 29e4357c..00000000 --- a/node_modules/.yarn-integrity +++ /dev/null @@ -1,10 +0,0 @@ -{ - "systemParams": "win32-x64-83", - "modulesFolders": [], - "flags": [], - "linkedModules": [], - "topLevelPatterns": [], - "lockfileEntries": {}, - "files": [], - "artifacts": {} -} \ No newline at end of file From 328b447cf44335883ce51109859f6f801e2515a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=A2=A6=E6=B4=81?= <3224935686@qq.com> Date: Thu, 7 Apr 2022 21:16:00 +0800 Subject: [PATCH 256/257] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0108.=E5=B0=86?= =?UTF-8?q?=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84=E8=BD=AC=E6=8D=A2=E4=B8=BA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md):=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0JavaScript=E8=BF=AD=E4=BB=A3=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0108.将有序数组转换为二叉搜索树.md | 40 ++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index bd5915fd..6ee3947b 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -355,6 +355,7 @@ func sortedArrayToBST(nums []int) *TreeNode { ``` ## JavaScript +递归 ```javascript var sortedArrayToBST = function (nums) { @@ -372,7 +373,44 @@ var sortedArrayToBST = function (nums) { return buildTree(nums, 0, nums.length - 1); }; ``` - +迭代 +```JavaScript +var sortedArrayToBST = function(nums) { + if(nums.length===0){ + return null; + } + let root=new TreeNode(0); //初始根节点 + let nodeQue=[root]; //放遍历的节点,并初始化 + let leftQue=[0]; //放左区间的下标,初始化 + let rightQue=[nums.length-1]; // 放右区间的下标 + + while(nodeQue.length){ + let curNode=nodeQue.pop(); + let left=leftQue.pop(); + let right=rightQue.pop(); + let mid=left+Math.floor((right-left)/2); + + curNode.val=nums[mid]; //将下标为mid的元素给中间节点 + +// 处理左区间 + if(left<=mid-1){ + curNode.left=new TreeNode(0); + nodeQue.push(curNode.left); + leftQue.push(left); + rightQue.push(mid-1); + } + +// 处理右区间 + if(right>=mid+1){ + curNode.right=new TreeNode(0); + nodeQue.push(curNode.right); + leftQue.push(mid+1); + rightQue.push(right); + } + } + return root; +}; +``` ## TypeScript ```typescript From 804d7e0171936ec370855ebb592fe123b731d8d8 Mon Sep 17 00:00:00 2001 From: programmercarl <826123027@qq.com> Date: Tue, 12 Apr 2022 22:23:28 +0800 Subject: [PATCH 257/257] delete $ --- problems/0063.不同路径II.md | 4 +- problems/0123.买卖股票的最佳时机III.md | 8 ++-- problems/0139.单词拆分.md | 2 +- problems/0151.翻转字符串里的单词.md | 2 +- problems/0343.整数拆分.md | 4 +- problems/0450.删除二叉搜索树中的节点.md | 2 +- problems/0503.下一个更大元素II.md | 2 +- problems/0674.最长连续递增序列.md | 10 ++-- ....买卖股票的最佳时机含手续费(动态规划).md | 8 ++-- problems/0844.比较含退格的字符串.md | 2 +- problems/0922.按奇偶排序数组II.md | 2 +- ...n)的算法居然超时了,此时的n究竟是多大?.md | 2 +- .../关于时间复杂度,你不知道的都在这里!.md | 6 +-- .../关于时间复杂度,你不知道的都在这里!.md | 46 +++++++++---------- .../前序/关于空间复杂度,可能有几个疑问?.md | 14 +++--- problems/前序/编程素养部分的吹毛求疵.md | 2 +- .../前序/递归算法的时间与空间复杂度分析.md | 26 +++++------ ...一道面试题目,讲一讲递归算法的时间复杂度!.md | 24 +++++----- problems/剑指Offer58-II.左旋转字符串.md | 2 +- problems/双指针总结.md | 2 +- problems/周总结/20200927二叉树周末总结.md | 2 +- problems/周总结/20201126贪心周末总结.md | 2 +- problems/周总结/20201210复杂度分析周末总结.md | 6 +-- problems/周总结/20201217贪心周末总结.md | 2 +- problems/周总结/20210225动规周末总结.md | 16 +++---- problems/哈希表理论基础.md | 14 +++--- problems/回溯总结.md | 2 +- problems/数组总结篇.md | 2 +- .../根据身高重建队列(vector原理讲解).md | 2 +- problems/贪心算法总结篇.md | 16 +------ 30 files changed, 111 insertions(+), 123 deletions(-) diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index c71cf796..a40cceda 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -184,8 +184,8 @@ public: }; ``` -* 时间复杂度:$O(n × m)$,n、m 分别为obstacleGrid 长度和宽度 -* 空间复杂度:$O(m)$ +* 时间复杂度:O(n × m),n、m 分别为obstacleGrid 长度和宽度 +* 空间复杂度:O(m) ## 总结 diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index fc81c3e9..56ade343 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -148,8 +148,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n × 5)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n × 5) 当然,大家可以看到力扣官方题解里的一种优化空间写法,我这里给出对应的C++版本: @@ -173,8 +173,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 大家会发现dp[2]利用的是当天的dp[1]。 但结果也是对的。 diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 7f1e6f17..ac834f04 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -207,7 +207,7 @@ public: }; ``` -* 时间复杂度:O(n^3),因为substr返回子串的副本是$O(n)$的复杂度(这里的n是substring的长度) +* 时间复杂度:O(n^3),因为substr返回子串的副本是O(n)的复杂度(这里的n是substring的长度) * 空间复杂度:O(n) diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 8dfe9bbc..4865821a 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -79,7 +79,7 @@ void removeExtraSpaces(string& s) { 逻辑很简单,从前向后遍历,遇到空格了就erase。 -如果不仔细琢磨一下erase的时间复杂读,还以为以上的代码是$O(n)$的时间复杂度呢。 +如果不仔细琢磨一下erase的时间复杂读,还以为以上的代码是O(n)的时间复杂度呢。 想一下真正的时间复杂度是多少,一个erase本来就是O(n)的操作,erase实现原理题目:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html),最优的算法来移除元素也要O(n)。 diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 777146ba..4a7ba6ab 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -119,8 +119,8 @@ public: }; ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(n) ### 贪心 diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index cc29bea4..e8f7e54c 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -51,7 +51,7 @@ if (root == nullptr) return root; * 确定单层递归的逻辑 -这里就把平衡二叉树中删除节点遇到的情况都搞清楚。 +这里就把二叉搜索树中删除节点遇到的情况都搞清楚。 有以下五种情况: diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index 36e183e1..ead31c8b 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -68,7 +68,7 @@ public: 这种写法确实比较直观,但做了很多无用操作,例如修改了nums数组,而且最后还要把result数组resize回去。 -resize倒是不费时间,是$O(1)$的操作,但扩充nums数组相当于多了一个$O(n)$的操作。 +resize倒是不费时间,是O(1)的操作,但扩充nums数组相当于多了一个O(n)的操作。 其实也可以不扩充nums,而是在遍历的过程中模拟走了两边nums。 diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 51d04e92..e941d242 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -107,8 +107,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ### 贪心 @@ -135,12 +135,12 @@ public: } }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) ## 总结 -本题也是动规里子序列问题的经典题目,但也可以用贪心来做,大家也会发现贪心好像更简单一点,而且空间复杂度仅是$O(1)$。 +本题也是动规里子序列问题的经典题目,但也可以用贪心来做,大家也会发现贪心好像更简单一点,而且空间复杂度仅是O(1)。 在动规分析中,关键是要理解和[动态规划:300.最长递增子序列](https://programmercarl.com/0300.最长上升子序列.html)的区别。 diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index b385d710..4ab63e79 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -38,8 +38,8 @@ 使用贪心算法,的性能是: -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 那么我们再来看看是使用动规的方法如何解题。 @@ -87,8 +87,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) ## 其他语言版本 diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 3bbfb73e..41791114 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -71,7 +71,7 @@ public: } }; ``` -* 时间复杂度:O(n + m),n为S的长度,m为T的长度 ,也可以理解是$O(n)$的时间复杂度 +* 时间复杂度:O(n + m),n为S的长度,m为T的长度 ,也可以理解是O(n)的时间复杂度 * 空间复杂度:O(n + m) 当然以上代码,大家可以发现有重复的逻辑处理S,处理T,可以把这块公共逻辑抽离出来,代码精简如下: diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 4ff419d3..cb564fb6 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -112,7 +112,7 @@ public: * 时间复杂度:O(n) * 空间复杂度:O(1) -这里时间复杂度并不是$O(n^2)$,因为偶数位和奇数位都只操作一次,不是n/2 * n/2的关系,而是n/2 + n/2的关系! +这里时间复杂度并不是O(n^2),因为偶数位和奇数位都只操作一次,不是n/2 * n/2的关系,而是n/2 + n/2的关系! ## 其他语言版本 diff --git a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md index 75f441db..24302b2d 100644 --- a/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md +++ b/problems/O(n)的算法居然超时了,此时的n究竟是多大?.md @@ -148,7 +148,7 @@ O(nlogn)的算法,1s内大概计算机可以运行 2 * (10^7)次计算,符 ![程序超时1](https://img-blog.csdnimg.cn/20201208231559175.png) -至于$O(\log n)$和$O(n^3)$ 等等这些时间复杂度在1s内可以处理的多大的数据规模,大家可以自己写一写代码去测一下了。 +至于O(log n)和O(n^3) 等等这些时间复杂度在1s内可以处理的多大的数据规模,大家可以自己写一写代码去测一下了。 # 完整测试代码 diff --git a/problems/关于时间复杂度,你不知道的都在这里!.md b/problems/关于时间复杂度,你不知道的都在这里!.md index 77fdacc4..a0fd6d92 100644 --- a/problems/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/关于时间复杂度,你不知道的都在这里!.md @@ -24,7 +24,7 @@ 算法导论给出的解释:**大O用来表示上界的**,当用它作为算法的最坏情况运行时间的上界,就是对任意数据输入的运行时间的上界。 -同样算法导论给出了例子:拿插入排序来说,插入排序的时间复杂度我们都说是$O(n^2)$ 。 +同样算法导论给出了例子:拿插入排序来说,插入排序的时间复杂度我们都说是O(n^2) 。 输入数据的形式对程序运算时间是有很大影响的,在数据本来有序的情况下时间复杂度是O(n),但如果数据是逆序的话,插入排序的时间复杂度就是O(n^2),也就对于所有输入情况来说,最坏是O(n^2) 的时间复杂度,所以称插入排序的时间复杂度为O(n^2)。 @@ -44,7 +44,7 @@ ![时间复杂度,不同数据规模的差异](https://img-blog.csdnimg.cn/20200728191447384.png) -在决定使用哪些算法的时候,不是时间复杂越低的越好(因为简化后的时间复杂度忽略了常数项等等),要考虑数据规模,如果数据规模很小甚至可以用$O(n^2)$的算法比$O(n)$的更合适(在有常数项的时候)。 +在决定使用哪些算法的时候,不是时间复杂越低的越好(因为简化后的时间复杂度忽略了常数项等等),要考虑数据规模,如果数据规模很小甚至可以用O(n^2)的算法比O(n)的更合适(在有常数项的时候)。 就像上图中 O(5n^2) 和 O(100n) 在n为20之前 很明显 O(5n^2)是更优的,所花费的时间也是最少的。 @@ -125,7 +125,7 @@ O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项 如果是暴力枚举的话,时间复杂度是多少呢,是O(n^2)么? -这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了n^2次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是$O(m × n × n)$。 +这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了n^2次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是O(m × n × n)。 接下来再想一下其他解题思路。 diff --git a/problems/前序/关于时间复杂度,你不知道的都在这里!.md b/problems/前序/关于时间复杂度,你不知道的都在这里!.md index b2acb7dd..f19984e6 100644 --- a/problems/前序/关于时间复杂度,你不知道的都在这里!.md +++ b/problems/前序/关于时间复杂度,你不知道的都在这里!.md @@ -9,7 +9,7 @@ * 什么是大O * 不同数据规模的差异 * 复杂表达式的化简 -* $O(\log n)$中的log是以什么为底? +* O(log n)中的log是以什么为底? * 举一个例子 @@ -23,21 +23,21 @@ 那么该如何估计程序运行时间呢,通常会估算算法的操作单元数量来代表程序消耗的时间,这里默认CPU的每个单元运行消耗的时间都是相同的。 -假设算法的问题规模为n,那么操作单元数量便用函数f(n)来表示,随着数据规模n的增大,算法执行时间的增长率和f(n)的增长率相同,这称作为算法的渐近时间复杂度,简称时间复杂度,记为 $O(f(n)$)。 +假设算法的问题规模为n,那么操作单元数量便用函数f(n)来表示,随着数据规模n的增大,算法执行时间的增长率和f(n)的增长率相同,这称作为算法的渐近时间复杂度,简称时间复杂度,记为 O(f(n))。 ## 什么是大O -这里的大O是指什么呢,说到时间复杂度,**大家都知道$O(n)$,$O(n^2)$,却说不清什么是大O**。 +这里的大O是指什么呢,说到时间复杂度,**大家都知道O(n),O(n^2),却说不清什么是大O**。 算法导论给出的解释:**大O用来表示上界的**,当用它作为算法的最坏情况运行时间的上界,就是对任意数据输入的运行时间的上界。 -同样算法导论给出了例子:拿插入排序来说,插入排序的时间复杂度我们都说是$O(n^2)$ 。 +同样算法导论给出了例子:拿插入排序来说,插入排序的时间复杂度我们都说是O(n^2) 。 -输入数据的形式对程序运算时间是有很大影响的,在数据本来有序的情况下时间复杂度是$O(n)$,但如果数据是逆序的话,插入排序的时间复杂度就是$O(n^2)$,也就对于所有输入情况来说,最坏是$O(n^2)$ 的时间复杂度,所以称插入排序的时间复杂度为$O(n^2)$。 +输入数据的形式对程序运算时间是有很大影响的,在数据本来有序的情况下时间复杂度是O(n),但如果数据是逆序的话,插入排序的时间复杂度就是O(n^2),也就对于所有输入情况来说,最坏是O(n^2) 的时间复杂度,所以称插入排序的时间复杂度为O(n^2)。 -同样的同理再看一下快速排序,都知道快速排序是$O(n\log n)$,但是当数据已经有序情况下,快速排序的时间复杂度是$O(n^2)$ 的,**所以严格从大O的定义来讲,快速排序的时间复杂度应该是$O(n^2)$**。 +同样的同理再看一下快速排序,都知道快速排序是O(nlogn),但是当数据已经有序情况下,快速排序的时间复杂度是O(n^2) 的,**所以严格从大O的定义来讲,快速排序的时间复杂度应该是O(n^2)**。 -**但是我们依然说快速排序是$O(n\log n)$的时间复杂度,这个就是业内的一个默认规定,这里说的O代表的就是一般情况,而不是严格的上界**。如图所示: +**但是我们依然说快速排序是O(nlogn)的时间复杂度,这个就是业内的一个默认规定,这里说的O代表的就是一般情况,而不是严格的上界**。如图所示: ![时间复杂度4,一般情况下的时间复杂度](https://img-blog.csdnimg.cn/20200728185745611.png) 我们主要关心的还是一般情况下的数据形式。 @@ -51,11 +51,11 @@ ![时间复杂度,不同数据规模的差异](https://img-blog.csdnimg.cn/20200728191447384.png) -在决定使用哪些算法的时候,不是时间复杂越低的越好(因为简化后的时间复杂度忽略了常数项等等),要考虑数据规模,如果数据规模很小甚至可以用$O(n^2)$的算法比$O(n)$的更合适(在有常数项的时候)。 +在决定使用哪些算法的时候,不是时间复杂越低的越好(因为简化后的时间复杂度忽略了常数项等等),要考虑数据规模,如果数据规模很小甚至可以用O(n^2)的算法比O(n)的更合适(在有常数项的时候)。 -就像上图中 $O(5n^2)$ 和 $O(100n)$ 在n为20之前 很明显 $O(5n^2)$是更优的,所花费的时间也是最少的。 +就像上图中 O(5n^2) 和 O(100n) 在n为20之前 很明显 O(5n^2)是更优的,所花费的时间也是最少的。 -那为什么在计算时间复杂度的时候要忽略常数项系数呢,也就说$O(100n)$ 就是$O(n)$的时间复杂度,$O(5n^2)$ 就是$O(n^2)$的时间复杂度,而且要默认$O(n)$ 优于$O(n^2)$ 呢 ? +那为什么在计算时间复杂度的时候要忽略常数项系数呢,也就说O(100n) 就是O(n)的时间复杂度,O(5n^2) 就是O(n^2)的时间复杂度,而且要默认O(n) 优于O(n^2) 呢 ? 这里就又涉及到大O的定义,**因为大O就是数据量级突破一个点且数据量级非常大的情况下所表现出的时间复杂度,这个数据量也就是常数项系数已经不起决定性作用的数据量**。 @@ -63,13 +63,13 @@ **所以我们说的时间复杂度都是省略常数项系数的,是因为一般情况下都是默认数据规模足够的大,基于这样的事实,给出的算法时间复杂的的一个排行如下所示**: -O(1)常数阶 < $O(\log n)$对数阶 < $O(n)$线性阶 < $O(n^2)$平方阶 < $O(n^3)$立方阶 < $O(2^n)$指数阶 +O(1)常数阶 < O(logn)对数阶 < O(n)线性阶 < O(n^2)平方阶 < O(n^3)立方阶 < O(2^n)指数阶 但是也要注意大常数,如果这个常数非常大,例如10^7 ,10^9 ,那么常数就是不得不考虑的因素了。 ## 复杂表达式的化简 -有时候我们去计算时间复杂度的时候发现不是一个简单的$O(n)$ 或者$O(n^2)$, 而是一个复杂的表达式,例如: +有时候我们去计算时间复杂度的时候发现不是一个简单的O(n) 或者O(n^2), 而是一个复杂的表达式,例如: ``` O(2*n^2 + 10*n + 1000) @@ -95,19 +95,19 @@ O(n^2 + n) O(n^2) ``` -如果这一步理解有困难,那也可以做提取n的操作,变成$O(n(n+1)$) ,省略加法常数项后也就别变成了: +如果这一步理解有困难,那也可以做提取n的操作,变成O(n(n+1)) ,省略加法常数项后也就别变成了: ``` O(n^2) ``` -所以最后我们说:这个算法的算法时间复杂度是$O(n^2)$ 。 +所以最后我们说:这个算法的算法时间复杂度是O(n^2) 。 -也可以用另一种简化的思路,其实当n大于40的时候, 这个复杂度会恒小于$O(3 × n^2)$, -$O(2 × n^2 + 10 × n + 1000) < O(3 × n^2)$,所以说最后省略掉常数项系数最终时间复杂度也是$O(n^2)$。 +也可以用另一种简化的思路,其实当n大于40的时候, 这个复杂度会恒小于O(3 × n^2), +O(2 × n^2 + 10 × n + 1000) < O(3 × n^2),所以说最后省略掉常数项系数最终时间复杂度也是O(n^2)。 -## $O(\log n)$中的log是以什么为底? +## O(logn)中的log是以什么为底? 平时说这个算法的时间复杂度是logn的,那么一定是log 以2为底n的对数么? @@ -130,21 +130,21 @@ $O(2 × n^2 + 10 × n + 1000) < O(3 × n^2)$,所以说最后省略掉常数项 通过这道面试题目,来分析一下时间复杂度。题目描述:找出n个字符串中相同的两个字符串(假设这里只有两个相同的字符串)。 -如果是暴力枚举的话,时间复杂度是多少呢,是$O(n^2)$么? +如果是暴力枚举的话,时间复杂度是多少呢,是O(n^2)么? -这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了n^2 次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是$O(m × n × n)$。 +这里一些同学会忽略了字符串比较的时间消耗,这里并不像int 型数字做比较那么简单,除了n^2 次的遍历次数外,字符串比较依然要消耗m次操作(m也就是字母串的长度),所以时间复杂度是O(m × n × n)。 接下来再想一下其他解题思路。 先排对n个字符串按字典序来排序,排序后n个字符串就是有序的,意味着两个相同的字符串就是挨在一起,然后在遍历一遍n个字符串,这样就找到两个相同的字符串了。 -那看看这种算法的时间复杂度,快速排序时间复杂度为$O(n\log n)$,依然要考虑字符串的长度是m,那么快速排序每次的比较都要有m次的字符比较的操作,就是$O(m × n × \log n)$ 。 +那看看这种算法的时间复杂度,快速排序时间复杂度为O(nlogn),依然要考虑字符串的长度是m,那么快速排序每次的比较都要有m次的字符比较的操作,就是O(m × n × log n) 。 -之后还要遍历一遍这n个字符串找出两个相同的字符串,别忘了遍历的时候依然要比较字符串,所以总共的时间复杂度是 $O(m × n × \log n + n × m)$。 +之后还要遍历一遍这n个字符串找出两个相同的字符串,别忘了遍历的时候依然要比较字符串,所以总共的时间复杂度是 O(m × n × logn + n × m)。 -我们对$O(m × n × \log n + n × m)$ 进行简化操作,把$m × n$提取出来变成 $O(m × n × (\log n + 1)$),再省略常数项最后的时间复杂度是 $O(m × n × \log n)$。 +我们对O(m × n × log n + n × m) 进行简化操作,把m × n提取出来变成 O(m × n × (logn + 1)),再省略常数项最后的时间复杂度是 O(m × n × log n)。 -最后很明显$O(m × n × \log n)$ 要优于$O(m × n × n)$! +最后很明显O(m × n × logn) 要优于O(m × n × n)! 所以先把字符串集合排序再遍历一遍找到两个相同字符串的方法要比直接暴力枚举的方式更快。 diff --git a/problems/前序/关于空间复杂度,可能有几个疑问?.md b/problems/前序/关于空间复杂度,可能有几个疑问?.md index 162dfe96..19384fd9 100644 --- a/problems/前序/关于空间复杂度,可能有几个疑问?.md +++ b/problems/前序/关于空间复杂度,可能有几个疑问?.md @@ -3,14 +3,14 @@ # 空间复杂度分析 * [关于时间复杂度,你不知道的都在这里!](https://programmercarl.com/前序/关于时间复杂度,你不知道的都在这里!.html) -* [$O(n)$的算法居然超时了,此时的n究竟是多大?](https://programmercarl.com/前序/On的算法居然超时了,此时的n究竟是多大?.html) +* [O(n)的算法居然超时了,此时的n究竟是多大?](https://programmercarl.com/前序/On的算法居然超时了,此时的n究竟是多大?.html) * [通过一道面试题目,讲一讲递归算法的时间复杂度!](https://programmercarl.com/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.html) 那么一直还没有讲空间复杂度,所以打算陆续来补上,内容不难,大家可以读一遍文章就有整体的了解了。 什么是空间复杂度呢? -是对一个算法在运行过程中占用内存空间大小的量度,记做$S(n)=O(f(n)$。 +是对一个算法在运行过程中占用内存空间大小的量度,记做S(n)=O(f(n)。 空间复杂度(Space Complexity)记作S(n) 依然使用大O来表示。利用程序的空间复杂度,可以对程序运行中需要多少内存有个预先估计。 @@ -41,11 +41,11 @@ for (int i = 0; i < n; i++) { } ``` -第一段代码可以看出,随着n的变化,所需开辟的内存空间并不会随着n的变化而变化。即此算法空间复杂度为一个常量,所以表示为大$O(1)$。 +第一段代码可以看出,随着n的变化,所需开辟的内存空间并不会随着n的变化而变化。即此算法空间复杂度为一个常量,所以表示为大O(1)。 -什么时候的空间复杂度是$O(n)$? +什么时候的空间复杂度是O(n)? -当消耗空间和输入参数n保持线性增长,这样的空间复杂度为$O(n)$,来看一下这段C++代码 +当消耗空间和输入参数n保持线性增长,这样的空间复杂度为O(n),来看一下这段C++代码 ```CPP int* a = new int(n); for (int i = 0; i < n; i++) { @@ -53,9 +53,9 @@ for (int i = 0; i < n; i++) { } ``` -我们定义了一个数组出来,这个数组占用的大小为n,虽然有一个for循环,但没有再分配新的空间,因此,这段代码的空间复杂度主要看第一行即可,随着n的增大,开辟的内存大小呈线性增长,即 $O(n)$。 +我们定义了一个数组出来,这个数组占用的大小为n,虽然有一个for循环,但没有再分配新的空间,因此,这段代码的空间复杂度主要看第一行即可,随着n的增大,开辟的内存大小呈线性增长,即 O(n)。 -其他的 $O(n^2)$, $O(n^3)$ 我想大家应该都可以以此例举出来了,**那么思考一下 什么时候空间复杂度是 $O(\log n)$呢?** +其他的 O(n^2), O(n^3) 我想大家应该都可以以此例举出来了,**那么思考一下 什么时候空间复杂度是 O(logn)呢?** 空间复杂度是logn的情况确实有些特殊,其实是在**递归的时候,会出现空间复杂度为logn的情况**。 diff --git a/problems/前序/编程素养部分的吹毛求疵.md b/problems/前序/编程素养部分的吹毛求疵.md index 3f18f9d1..6099747a 100644 --- a/problems/前序/编程素养部分的吹毛求疵.md +++ b/problems/前序/编程素养部分的吹毛求疵.md @@ -13,7 +13,7 @@ - 左孩子和右孩子的下标不太好理解。我给出证明过程: - 如果父节点在第$k$层,第$m,m \in [0,2^k]$个节点,则其左孩子所在的位置必然为$k+1$层,第$2*(m-1)+1$个节点。 + 如果父节点在第k层,第$m,m \in [0,2^k]$个节点,则其左孩子所在的位置必然为$k+1$层,第$2*(m-1)+1$个节点。 - 计算父节点在数组中的索引: $$ diff --git a/problems/前序/递归算法的时间与空间复杂度分析.md b/problems/前序/递归算法的时间与空间复杂度分析.md index 3c0d219c..142358da 100644 --- a/problems/前序/递归算法的时间与空间复杂度分析.md +++ b/problems/前序/递归算法的时间与空间复杂度分析.md @@ -26,7 +26,7 @@ int fibonacci(int i) { 在讲解递归时间复杂度的时候,我们提到了递归算法的时间复杂度本质上是要看: **递归的次数 * 每次递归的时间复杂度**。 -可以看出上面的代码每次递归都是$O(1)$的操作。再来看递归了多少次,这里将i为5作为输入的递归过程 抽象成一棵递归树,如图: +可以看出上面的代码每次递归都是O(1)的操作。再来看递归了多少次,这里将i为5作为输入的递归过程 抽象成一棵递归树,如图: ![递归空间复杂度分析](https://img-blog.csdnimg.cn/20210305093200104.png) @@ -36,7 +36,7 @@ int fibonacci(int i) { 我们之前也有说到,一棵深度(按根节点深度为1)为k的二叉树最多可以有 2^k - 1 个节点。 -所以该递归算法的时间复杂度为$O(2^n)$,这个复杂度是非常大的,随着n的增大,耗时是指数上升的。 +所以该递归算法的时间复杂度为O(2^n),这个复杂度是非常大的,随着n的增大,耗时是指数上升的。 来做一个实验,大家可以有一个直观的感受。 @@ -85,7 +85,7 @@ int main() * n = 40,耗时:837 ms * n = 50,耗时:110306 ms -可以看出,$O(2^n)$这种指数级别的复杂度是非常大的。 +可以看出,O(2^n)这种指数级别的复杂度是非常大的。 所以这种求斐波那契数的算法看似简洁,其实时间复杂度非常高,一般不推荐这样来实现斐波那契。 @@ -119,14 +119,14 @@ int fibonacci(int first, int second, int n) { 这里相当于用first和second来记录当前相加的两个数值,此时就不用两次递归了。 -因为每次递归的时候n减1,即只是递归了n次,所以时间复杂度是 $O(n)$。 +因为每次递归的时候n减1,即只是递归了n次,所以时间复杂度是 O(n)。 -同理递归的深度依然是n,每次递归所需的空间也是常数,所以空间复杂度依然是$O(n)$。 +同理递归的深度依然是n,每次递归所需的空间也是常数,所以空间复杂度依然是O(n)。 代码(版本二)的复杂度如下: -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 此时再来测一下耗时情况验证一下: @@ -198,7 +198,7 @@ int main() 递归第n个斐波那契数的话,递归调用栈的深度就是n。 -那么每次递归的空间复杂度是$O(1)$, 调用栈深度为n,所以这段递归代码的空间复杂度就是$O(n)$。 +那么每次递归的空间复杂度是O(1), 调用栈深度为n,所以这段递归代码的空间复杂度就是O(n)。 ```CPP int fibonacci(int i) { @@ -233,24 +233,24 @@ int binary_search( int arr[], int l, int r, int x) { } ``` -都知道二分查找的时间复杂度是$O(\log n)$,那么递归二分查找的空间复杂度是多少呢? +都知道二分查找的时间复杂度是O(logn),那么递归二分查找的空间复杂度是多少呢? 我们依然看 **每次递归的空间复杂度和递归的深度** 每次递归的空间复杂度可以看出主要就是参数里传入的这个arr数组,但需要注意的是在C/C++中函数传递数组参数,不是整个数组拷贝一份传入函数而是传入的数组首元素地址。 -**也就是说每一层递归都是公用一块数组地址空间的**,所以 每次递归的空间复杂度是常数即:$O(1)$。 +**也就是说每一层递归都是公用一块数组地址空间的**,所以 每次递归的空间复杂度是常数即:O(1)。 -再来看递归的深度,二分查找的递归深度是logn ,递归深度就是调用栈的长度,那么这段代码的空间复杂度为 $1 * logn = O(logn)$。 +再来看递归的深度,二分查找的递归深度是logn ,递归深度就是调用栈的长度,那么这段代码的空间复杂度为 1 * logn = O(logn)。 -大家要注意自己所用的语言在传递函数参数的时,是拷贝整个数值还是拷贝地址,如果是拷贝整个数值那么该二分法的空间复杂度就是$O(n\log n)$。 +大家要注意自己所用的语言在传递函数参数的时,是拷贝整个数值还是拷贝地址,如果是拷贝整个数值那么该二分法的空间复杂度就是O(nlogn)。 ## 总结 本章我们详细分析了递归实现的求斐波那契和二分法的空间复杂度,同时也对时间复杂度做了分析。 -特别是两种递归实现的求斐波那契数列,其时间复杂度截然不容,我们还做了实验,验证了时间复杂度为$O(2^n)$是非常耗时的。 +特别是两种递归实现的求斐波那契数列,其时间复杂度截然不容,我们还做了实验,验证了时间复杂度为O(2^n)是非常耗时的。 通过本篇大家应该对递归算法的时间复杂度和空间复杂度有更加深刻的理解了。 diff --git a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md index 12af4dd8..b2db92f5 100644 --- a/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md +++ b/problems/前序/通过一道面试题目,讲一讲递归算法的时间复杂度!.md @@ -5,13 +5,13 @@ 相信很多同学对递归算法的时间复杂度都很模糊,那么这篇来给大家通透的讲一讲。 -**同一道题目,同样使用递归算法,有的同学会写出了$O(n)$的代码,有的同学就写出了$O(\log n)$的代码**。 +**同一道题目,同样使用递归算法,有的同学会写出了O(n)的代码,有的同学就写出了O(logn)的代码**。 这是为什么呢? 如果对递归的时间复杂度理解的不够深入的话,就会这样! -那么我通过一道简单的面试题,模拟面试的场景,来带大家逐步分析递归算法的时间复杂度,最后找出最优解,来看看同样是递归,怎么就写成了$O(n)$的代码。 +那么我通过一道简单的面试题,模拟面试的场景,来带大家逐步分析递归算法的时间复杂度,最后找出最优解,来看看同样是递归,怎么就写成了O(n)的代码。 面试题:求x的n次方 @@ -26,7 +26,7 @@ int function1(int x, int n) { return result; } ``` -时间复杂度为$O(n)$,此时面试官会说,有没有效率更好的算法呢。 +时间复杂度为O(n),此时面试官会说,有没有效率更好的算法呢。 **如果此时没有思路,不要说:我不会,我不知道了等等**。 @@ -44,11 +44,11 @@ int function2(int x, int n) { ``` 面试官问:“那么这个代码的时间复杂度是多少?”。 -一些同学可能一看到递归就想到了$O(\log n)$,其实并不是这样,递归算法的时间复杂度本质上是要看: **递归的次数 * 每次递归中的操作次数**。 +一些同学可能一看到递归就想到了O(log n),其实并不是这样,递归算法的时间复杂度本质上是要看: **递归的次数 * 每次递归中的操作次数**。 那再来看代码,这里递归了几次呢? -每次n-1,递归了n次时间复杂度是$O(n)$,每次进行了一个乘法操作,乘法操作的时间复杂度一个常数项$O(1)$,所以这份代码的时间复杂度是 $n × 1 = O(n)$。 +每次n-1,递归了n次时间复杂度是O(n),每次进行了一个乘法操作,乘法操作的时间复杂度一个常数项O(1),所以这份代码的时间复杂度是 n × 1 = O(n)。 这个时间复杂度就没有达到面试官的预期。于是又写出了如下的递归算法的代码: @@ -81,11 +81,11 @@ int function3(int x, int n) { ![递归求时间复杂度](https://img-blog.csdnimg.cn/20200728195531892.png) -**时间复杂度忽略掉常数项`-1`之后,这个递归算法的时间复杂度依然是$O(n)$**。对,你没看错,依然是$O(n)$的时间复杂度! +**时间复杂度忽略掉常数项`-1`之后,这个递归算法的时间复杂度依然是O(n)**。对,你没看错,依然是O(n)的时间复杂度! -此时面试官就会说:“这个递归的算法依然还是$O(n)$啊”, 很明显没有达到面试官的预期。 +此时面试官就会说:“这个递归的算法依然还是O(n)啊”, 很明显没有达到面试官的预期。 -那么$O(\log n)$的递归算法应该怎么写呢? +那么O(logn)的递归算法应该怎么写呢? 想一想刚刚给出的那份递归算法的代码,是不是有哪里比较冗余呢,其实有重复计算的部分。 @@ -108,7 +108,7 @@ int function4(int x, int n) { 依然还是看他递归了多少次,可以看到这里仅仅有一个递归调用,且每次都是n/2 ,所以这里我们一共调用了log以2为底n的对数次。 -**每次递归了做都是一次乘法操作,这也是一个常数项的操作,那么这个递归算法的时间复杂度才是真正的$O(\log n)$**。 +**每次递归了做都是一次乘法操作,这也是一个常数项的操作,那么这个递归算法的时间复杂度才是真正的O(logn)**。 此时大家最后写出了这样的代码并且将时间复杂度分析的非常清晰,相信面试官是比较满意的。 @@ -116,11 +116,11 @@ int function4(int x, int n) { 对于递归的时间复杂度,毕竟初学者有时候会迷糊,刷过很多题的老手依然迷糊。 -**本篇我用一道非常简单的面试题目:求x的n次方,来逐步分析递归算法的时间复杂度,注意不要一看到递归就想到了$O(\log n)$!** +**本篇我用一道非常简单的面试题目:求x的n次方,来逐步分析递归算法的时间复杂度,注意不要一看到递归就想到了O(logn)!** -同样使用递归,有的同学可以写出$O(\log n)$的代码,有的同学还可以写出$O(n)$的代码。 +同样使用递归,有的同学可以写出O(logn)的代码,有的同学还可以写出O(n)的代码。 -对于function3 这样的递归实现,很容易让人感觉这是$O(\log n)$的时间复杂度,其实这是$O(n)$的算法! +对于function3 这样的递归实现,很容易让人感觉这是O(log n)的时间复杂度,其实这是O(n)的算法! ```CPP int function3(int x, int n) { diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 61391274..fec83e1d 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -86,7 +86,7 @@ public: # 题外话 一些同学热衷于使用substr,来做这道题。 -其实使用substr 和 反转 时间复杂度是一样的 ,都是$O(n)$,但是使用substr申请了额外空间,所以空间复杂度是$O(n)$,而反转方法的空间复杂度是$O(1)$。 +其实使用substr 和 反转 时间复杂度是一样的 ,都是O(n),但是使用substr申请了额外空间,所以空间复杂度是O(n),而反转方法的空间复杂度是O(1)。 **如果想让这套题目有意义,就不要申请额外空间。** diff --git a/problems/双指针总结.md b/problems/双指针总结.md index 39096ff7..06752cac 100644 --- a/problems/双指针总结.md +++ b/problems/双指针总结.md @@ -89,7 +89,7 @@ for (int i = 0; i < array.size(); i++) { # 总结 -本文中一共介绍了leetcode上九道使用双指针解决问题的经典题目,除了链表一些题目一定要使用双指针,其他题目都是使用双指针来提高效率,一般是将$O(n^2)$的时间复杂度,降为$O(n)$。 +本文中一共介绍了leetcode上九道使用双指针解决问题的经典题目,除了链表一些题目一定要使用双指针,其他题目都是使用双指针来提高效率,一般是将O(n^2)的时间复杂度,降为$O(n)$。 建议大家可以把文中涉及到的题目在好好做一做,琢磨琢磨,基本对双指针法就不在话下了。 diff --git a/problems/周总结/20200927二叉树周末总结.md b/problems/周总结/20200927二叉树周末总结.md index 60f02205..ff8f67d4 100644 --- a/problems/周总结/20200927二叉树周末总结.md +++ b/problems/周总结/20200927二叉树周末总结.md @@ -44,7 +44,7 @@ a->right = NULL; 在介绍前中后序遍历的时候,有递归和迭代(非递归),还有一种牛逼的遍历方式:morris遍历。 -morris遍历是二叉树遍历算法的超强进阶算法,morris遍历可以将非递归遍历中的空间复杂度降为$O(1)$,感兴趣大家就去查一查学习学习,比较小众,面试几乎不会考。我其实也没有研究过,就不做过多介绍了。 +morris遍历是二叉树遍历算法的超强进阶算法,morris遍历可以将非递归遍历中的空间复杂度降为O(1),感兴趣大家就去查一查学习学习,比较小众,面试几乎不会考。我其实也没有研究过,就不做过多介绍了。 ## 周二 diff --git a/problems/周总结/20201126贪心周末总结.md b/problems/周总结/20201126贪心周末总结.md index 02fccc25..e310c0f8 100644 --- a/problems/周总结/20201126贪心周末总结.md +++ b/problems/周总结/20201126贪心周末总结.md @@ -41,7 +41,7 @@ 一些录友不清楚[贪心算法:分发饼干](https://programmercarl.com/0455.分发饼干.html)中时间复杂度是怎么来的? -就是快排$O(n\log n)$,遍历$O(n)$,加一起就是还是$O(n\log n)$。 +就是快排O(nlog n),遍历O(n),加一起就是还是O(nlogn)。 ## 周三 diff --git a/problems/周总结/20201210复杂度分析周末总结.md b/problems/周总结/20201210复杂度分析周末总结.md index 1b404bf0..5e5f696d 100644 --- a/problems/周总结/20201210复杂度分析周末总结.md +++ b/problems/周总结/20201210复杂度分析周末总结.md @@ -70,9 +70,9 @@ # 周三 -在[$O(n)$的算法居然超时了,此时的n究竟是多大?](https://programmercarl.com/前序/On的算法居然超时了,此时的n究竟是多大?.html)中介绍了大家在leetcode上提交代码经常遇到的一个问题-超时! +在[O(n)的算法居然超时了,此时的n究竟是多大?](https://programmercarl.com/前序/On的算法居然超时了,此时的n究竟是多大?.html)中介绍了大家在leetcode上提交代码经常遇到的一个问题-超时! -估计很多录友知道算法超时了,但没有注意过 $O(n)$的算法,如果1s内出结果,这个n究竟是多大? +估计很多录友知道算法超时了,但没有注意过 O(n)的算法,如果1s内出结果,这个n究竟是多大? 文中从计算机硬件出发,分析计算机的计算性能,然后亲自做实验,整理出数据如下: @@ -95,7 +95,7 @@ 文中给出了四个版本的代码实现,并逐一分析了其时间复杂度。 -此时大家就会发现,同一道题目,同样使用递归算法,有的同学会写出了$O(n)$的代码,有的同学就写出了$O(\log n)$的代码。 +此时大家就会发现,同一道题目,同样使用递归算法,有的同学会写出了O(n)的代码,有的同学就写出了$O(\log n)$的代码。 其本质是要对递归的时间复杂度有清晰的认识,才能运用递归来有效的解决问题! diff --git a/problems/周总结/20201217贪心周末总结.md b/problems/周总结/20201217贪心周末总结.md index e9d22d6e..4d12f92a 100644 --- a/problems/周总结/20201217贪心周末总结.md +++ b/problems/周总结/20201217贪心周末总结.md @@ -8,7 +8,7 @@ 在[贪心算法:加油站](https://programmercarl.com/0134.加油站.html)中给出每一个加油站的汽油和开到这个加油站的消耗,问汽车能不能开一圈。 -这道题目咋眼一看,感觉是一道模拟题,模拟一下汽车从每一个节点出发看看能不能开一圈,时间复杂度是$O(n^2)$。 +这道题目咋眼一看,感觉是一道模拟题,模拟一下汽车从每一个节点出发看看能不能开一圈,时间复杂度是O(n^2)。 即使用模拟这种情况,也挺考察代码技巧的。 diff --git a/problems/周总结/20210225动规周末总结.md b/problems/周总结/20210225动规周末总结.md index 0bf9dbdb..21cc53ad 100644 --- a/problems/周总结/20210225动规周末总结.md +++ b/problems/周总结/20210225动规周末总结.md @@ -211,8 +211,8 @@ public: }; ``` -* 时间复杂度:$O(n^2)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n^2) +* 空间复杂度:O(1) 贪心解法代码如下: @@ -233,8 +233,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 动规解法,版本一,代码如下: @@ -256,8 +256,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(n)$ +* 时间复杂度:O(n) +* 空间复杂度:O(n) 从递推公式可以看出,dp[i]只是依赖于dp[i - 1]的状态。 @@ -282,8 +282,8 @@ public: }; ``` -* 时间复杂度:$O(n)$ -* 空间复杂度:$O(1)$ +* 时间复杂度:O(n) +* 空间复杂度:O(1) 建议先写出版本一,然后在版本一的基础上优化成版本二,而不是直接就写出版本二。 diff --git a/problems/哈希表理论基础.md b/problems/哈希表理论基础.md index 40a8d0ca..3b6c5ce5 100644 --- a/problems/哈希表理论基础.md +++ b/problems/哈希表理论基础.md @@ -22,7 +22,7 @@ 例如要查询一个名字是否在这所学校里。 -要枚举的话时间复杂度是$O(n)$,但如果使用哈希表的话, 只需要$O(1)$就可以做到。 +要枚举的话时间复杂度是O(n),但如果使用哈希表的话, 只需要O(1)就可以做到。 我们只需要初始化把这所学校里学生的名字都存在哈希表里,在查询的时候通过索引直接就可以知道这位同学在不在这所学校里了。 @@ -88,17 +88,17 @@ |集合 |底层实现 | 是否有序 |数值是否可以重复 | 能否更改数值|查询效率 |增删效率| |---|---| --- |---| --- | --- | ---| -|std::set |红黑树 |有序 |否 |否 | $O(\log n)$|$O(\log n)$ | -|std::multiset | 红黑树|有序 |是 | 否| $O(\log n)$ |$O(\log n)$ | -|std::unordered_set |哈希表 |无序 |否 |否 |$O(1)$ | $O(1)$| +|std::set |红黑树 |有序 |否 |否 | O(log n)|O(log n) | +|std::multiset | 红黑树|有序 |是 | 否| O(logn) |O(logn) | +|std::unordered_set |哈希表 |无序 |否 |否 |O(1) | O(1)| std::unordered_set底层实现为哈希表,std::set 和std::multiset 的底层实现是红黑树,红黑树是一种平衡二叉搜索树,所以key值是有序的,但key不可以修改,改动key值会导致整棵树的错乱,所以只能删除和增加。 |映射 |底层实现 | 是否有序 |数值是否可以重复 | 能否更改数值|查询效率 |增删效率| |---|---| --- |---| --- | --- | ---| -|std::map |红黑树 |key有序 |key不可重复 |key不可修改 | $O(\log n)$|$O(\log n)$ | -|std::multimap | 红黑树|key有序 | key可重复 | key不可修改|$O(\log n)$ |$O(\log n)$ | -|std::unordered_map |哈希表 | key无序 |key不可重复 |key不可修改 |$O(1)$ | $O(1)$| +|std::map |红黑树 |key有序 |key不可重复 |key不可修改 | O(logn)|O(logn) | +|std::multimap | 红黑树|key有序 | key可重复 | key不可修改|O(log n) |O(log n) | +|std::unordered_map |哈希表 | key无序 |key不可重复 |key不可修改 |O(1) | O(1)| std::unordered_map 底层实现为哈希表,std::map 和std::multimap 的底层实现是红黑树。同理,std::map 和std::multimap 的key也是有序的(这个问题也经常作为面试题,考察对语言容器底层的理解)。 diff --git a/problems/回溯总结.md b/problems/回溯总结.md index 5b8e2276..54ac485b 100644 --- a/problems/回溯总结.md +++ b/problems/回溯总结.md @@ -302,7 +302,7 @@ if (startIndex >= nums.size()) { // 终止条件可以不加 **而使用used数组在时间复杂度上几乎没有额外负担!** -**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是O(n),但如果使用set去重,空间复杂度就变成了$O(n^2)$,因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 +**使用set去重,不仅时间复杂度高了,空间复杂度也高了**,在[本周小结!(回溯算法系列三)](https://programmercarl.com/周总结/20201112回溯周末总结.html)中分析过,组合,子集,排列问题的空间复杂度都是O(n),但如果使用set去重,空间复杂度就变成了O(n^2),因为每一层递归都有一个set集合,系统栈空间是n,每一个空间都有set集合。 那有同学可能疑惑 用used数组也是占用O(n)的空间啊? diff --git a/problems/数组总结篇.md b/problems/数组总结篇.md index 242c1498..d256298b 100644 --- a/problems/数组总结篇.md +++ b/problems/数组总结篇.md @@ -102,7 +102,7 @@ 本题中,主要要理解滑动窗口如何移动 窗口起始位置,达到动态更新窗口大小的,从而得出长度最小的符合条件的长度。 -**滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将$O(n^2)$的暴力解法降为$O(n)$。** +**滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)的暴力解法降为O(n)。** 如果没有接触过这一类的方法,很难想到类似的解题思路,滑动窗口方法还是很巧妙的。 diff --git a/problems/根据身高重建队列(vector原理讲解).md b/problems/根据身高重建队列(vector原理讲解).md index 6c972b41..e229f397 100644 --- a/problems/根据身高重建队列(vector原理讲解).md +++ b/problems/根据身高重建队列(vector原理讲解).md @@ -151,7 +151,7 @@ public: 大家应该发现了,编程语言中一个普通容器的insert,delete的使用,都可能对写出来的算法的有很大影响! -如果抛开语言谈算法,除非从来不用代码写算法纯分析,**否则的话,语言功底不到位O(n)的算法可以写出$O(n^2)$的性能**,哈哈。 +如果抛开语言谈算法,除非从来不用代码写算法纯分析,**否则的话,语言功底不到位O(n)的算法可以写出O(n^2)的性能**,哈哈。 相信在这里学习算法的录友们,都是想在软件行业长远发展的,都是要从事编程的工作,那么一定要深耕好一门编程语言,这个非常重要! diff --git a/problems/贪心算法总结篇.md b/problems/贪心算法总结篇.md index 1db9b4dc..6539501f 100644 --- a/problems/贪心算法总结篇.md +++ b/problems/贪心算法总结篇.md @@ -127,9 +127,9 @@ Carl个人认为:如果找出局部最优并可以推出全局最优,就是 贪心专题汇聚为一张图: -![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211110121605.png) +![](https://code-thinking-1253855093.file.myqcloud.com/pics/贪心总结water.png) -这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[青](https://wx.zsxq.com/dweb2/index/footprint/185251215558842)所画,总结的非常好,分享给大家。 +这个图是 [代码随想录知识星球](https://programmercarl.com/other/kstar.html) 成员:[海螺人](https://wx.zsxq.com/dweb2/index/footprint/844412858822412)所画,总结的非常好,分享给大家。 很多没有接触过贪心的同学都会感觉贪心有啥可学的,但只要跟着「代码随想录」坚持下来之后,就会发现,贪心是一种很重要的算法思维而且并不简单,贪心往往妙的出其不意,触不及防! @@ -145,18 +145,6 @@ Carl个人认为:如果找出局部最优并可以推出全局最优,就是 **一个系列的结束,又是一个新系列的开始,我们将在明年第一个工作日正式开始动态规划,来不及解释了,录友们上车别掉队,我们又要开始新的征程!** -## 其他语言版本 - - -Java: - - -Python: - - -Go: - - -----------------------