From eb8d3279a8640cbcce4d8e9d734f4222ba8fd8e4 Mon Sep 17 00:00:00 2001 From: SunnyQjm Date: Sun, 28 Jun 2020 10:42:08 +0800 Subject: [PATCH] update --- chapter10/3_binary-tree-paths.py | 6 ++--- .../4_kth-largest-element-in-a-stream.py | 11 +++++----- chapter11/1_implement-trie.py | 14 +++++------- chapter11/2_longest-word-in-dictionary.py | 3 ++- ...ree-from-preorder-and-inorder-traversal.py | 7 +++--- .../5_binary-tree-level-order-traversal.py | 4 +++- .../1_cheapest-flights-within-k-steps.py | 4 +++- chapter12/3_top-k-frequent-words.py | 1 + .../2_shortest-path-visiting-all-nodes.py | 1 + chapter9/1_edit-distance.py | 3 ++- chapter9/2_burst-ballons.py | 12 +++++----- chapter9/3_my-calendar-i.py | 2 +- chapter9/7_binary-tree-preorder-traversal.py | 22 +++++++++++++++++++ 13 files changed, 58 insertions(+), 32 deletions(-) diff --git a/chapter10/3_binary-tree-paths.py b/chapter10/3_binary-tree-paths.py index 8f37412..e41d358 100644 --- a/chapter10/3_binary-tree-paths.py +++ b/chapter10/3_binary-tree-paths.py @@ -49,8 +49,8 @@ class Solution: return if not root.left and not root.right: result.append(s + "->" + str(root.val)) - preOrderTraversal(root.left, s + "->" + str(root.val), result) - preOrderTraversal(root.right, s + "->" + str(root.val), result) + preorderTraversal(root.left, s + "->" + str(root.val), result) + preorderTraversal(root.right, s + "->" + str(root.val), result) if not root: return [] @@ -58,6 +58,6 @@ class Solution: return [str(root.val)] s = str(root.val) result = [] - preOrderTraversal(root, s, result) + preorderTraversal(root, s, result) return result diff --git a/chapter10/4_kth-largest-element-in-a-stream.py b/chapter10/4_kth-largest-element-in-a-stream.py index 7a5b003..fe8252b 100644 --- a/chapter10/4_kth-largest-element-in-a-stream.py +++ b/chapter10/4_kth-largest-element-in-a-stream.py @@ -23,6 +23,7 @@ import heapq + class KthLargest: def __init__(self, k, nums): @@ -31,14 +32,13 @@ class KthLargest: :type nums: List[int] """ self.heap = nums - heapq.heapify(self.heap) # 用一个列表作为堆(使用heapq对其操作) - self.currentSize = len(nums) # 保存当前堆中元素的个数 + heapq.heapify(self.heap) # 用一个列表作为堆(使用heapq对其操作) + self.currentSize = len(nums) # 保存当前堆中元素的个数 self.k = k while self.currentSize > k: heapq.heappop(self.heap) self.currentSize -= 1 - def add(self, val): """ :type val: int @@ -52,11 +52,11 @@ class KthLargest: 3. 每次插入时执行以下流程: - 首先判断当前堆的大小是k还是k-1;(因为题目中指出,nums >= k-1,所以初始堆中元素个数至少为k-1,又因为我们在初始化时进行了堆删除,删到小于等于k为止,所以堆中元素最多有k个) - 如果currentSize == k-1,则插入当前元素到堆中,并返回堆顶元素即可; - - 如果currentSuze > k-1, 则将当前元素插入到堆中,接着再删除堆顶元素,并返回堆顶元素;(这样可以保证堆中元素一直是k个) + - 如果currentSize > k-1, 则将当前元素插入到堆中,接着再删除堆顶元素,并返回堆顶元素;(这样可以保证堆中元素一直是k个) """ if self.currentSize == self.k - 1: heapq.heappush(self.heap, val) - self.size += 1 + self.currentSize += 1 else: heapq.heappush(self.heap, val) heapq.heappop(self.heap) @@ -71,4 +71,3 @@ if __name__ == '__main__': print(kthLargest.add(10), "= 5") print(kthLargest.add(9), "= 8") print(kthLargest.add(4), "= 8") - diff --git a/chapter11/1_implement-trie.py b/chapter11/1_implement-trie.py index e0ceb80..2bcd915 100644 --- a/chapter11/1_implement-trie.py +++ b/chapter11/1_implement-trie.py @@ -21,10 +21,12 @@ # - 保证所有输入均为非空字符串。 ####################################################################################### + class TreeNode: def __init__(self): - self.word = False # 表示当前节点是否是一个曾经插入的单词 - self.children = {} # 子节点列表 + self.word = False # 表示当前节点是否是一个曾经插入的单词 + self.children = {} # 子节点列表 + class Trie: @@ -34,7 +36,6 @@ class Trie: """ self.root = TreeNode() - def insert(self, word: str) -> None: """ Inserts a word into the trie. @@ -42,12 +43,11 @@ class Trie: # 从根节点出发 node = self.root for char in word: - if char not in node.children: # 判断当前字符是否在当前节点的子节点里面,不在,则创建一个子节点 + if char not in node.children: # 判断当前字符是否在当前节点的子节点里面,不在,则创建一个子节点 node.children[char] = TreeNode() - node = node.children[char] # 跳到对应的子节点 + node = node.children[char] # 跳到对应的子节点 node.word = True - def search(self, word: str) -> bool: """ Returns if the word is in the trie. @@ -59,7 +59,6 @@ class Trie: node = node.children[char] return node.word - def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. @@ -72,7 +71,6 @@ class Trie: return True - # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) diff --git a/chapter11/2_longest-word-in-dictionary.py b/chapter11/2_longest-word-in-dictionary.py index a90f369..4100cd9 100644 --- a/chapter11/2_longest-word-in-dictionary.py +++ b/chapter11/2_longest-word-in-dictionary.py @@ -29,6 +29,7 @@ from typing import List + class Solution: def longestWord(self, words: List[str]) -> str: """ @@ -44,7 +45,7 @@ class Solution: 4. 最后对valid进行按字典序排序,然后返回长度最大的元素即可 """ - valid = set([""]) + valid = {""} for word in sorted(words, key=len): if word[:-1] in valid: diff --git a/chapter11/3_construct-binary-tree-from-preorder-and-inorder-traversal.py b/chapter11/3_construct-binary-tree-from-preorder-and-inorder-traversal.py index 5f729cd..3a6441d 100644 --- a/chapter11/3_construct-binary-tree-from-preorder-and-inorder-traversal.py +++ b/chapter11/3_construct-binary-tree-from-preorder-and-inorder-traversal.py @@ -23,6 +23,7 @@ from typing import List + class TreeNode: def __init__(self, x): self.val = x @@ -57,7 +58,7 @@ class Solution: if not preorder: return None root = TreeNode(preorder[0]) - + # 用于记录左右子树的元素个数 leftNum, rightNum = 0, 0 @@ -66,8 +67,8 @@ class Solution: break leftNum += 1 - root.left = self.buildTree(preorder[1:1+leftNum], inorder[0:leftNum]) - root.right = self.buildTree(preorder[1+leftNum:], inorder[leftNum + 1:]) + root.left = self.buildTree(preorder[1:1 + leftNum], inorder[0:leftNum]) + root.right = self.buildTree(preorder[1 + leftNum:], inorder[leftNum + 1:]) return root diff --git a/chapter11/5_binary-tree-level-order-traversal.py b/chapter11/5_binary-tree-level-order-traversal.py index 9d46060..1148e37 100644 --- a/chapter11/5_binary-tree-level-order-traversal.py +++ b/chapter11/5_binary-tree-level-order-traversal.py @@ -26,6 +26,7 @@ from typing import List import collections + class TreeNode: def __init__(self, x): self.val = x @@ -36,6 +37,7 @@ class TreeNode: if self: return "{}->{}->{}".format(self.val, repr(self.left), repr(self.right)) + class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: """ @@ -75,7 +77,7 @@ class Solution: queue.append(curNode.right) nextLevelNum += 1 - if curLevelNum == 0: # 判断是否换层 + if curLevelNum == 0: # 判断是否换层 curLevelNum, nextLevelNum = nextLevelNum, 0 # 如果下一层还有可遍历的节点,则往结果集里面新加一个空列表用来存储下一层的遍历结果 if curLevelNum != 0: diff --git a/chapter12/1_cheapest-flights-within-k-steps.py b/chapter12/1_cheapest-flights-within-k-steps.py index 49a7e66..f1072fe 100644 --- a/chapter12/1_cheapest-flights-within-k-steps.py +++ b/chapter12/1_cheapest-flights-within-k-steps.py @@ -7,8 +7,10 @@ # 题目太长了,瞅这 => https://leetcode-cn.com/problems/cheapest-flights-within-k-stops/ ####################################################################################### +import collections +import heapq from typing import List -import collections, heapq + class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: diff --git a/chapter12/3_top-k-frequent-words.py b/chapter12/3_top-k-frequent-words.py index 40028a0..64010bf 100644 --- a/chapter12/3_top-k-frequent-words.py +++ b/chapter12/3_top-k-frequent-words.py @@ -30,6 +30,7 @@ from typing import List import collections + class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: """ diff --git a/chapter13/2_shortest-path-visiting-all-nodes.py b/chapter13/2_shortest-path-visiting-all-nodes.py index 58ec497..82820ad 100644 --- a/chapter13/2_shortest-path-visiting-all-nodes.py +++ b/chapter13/2_shortest-path-visiting-all-nodes.py @@ -26,6 +26,7 @@ import collections from typing import List + class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: """ diff --git a/chapter9/1_edit-distance.py b/chapter9/1_edit-distance.py index ed5d5a4..6d0b9c9 100644 --- a/chapter9/1_edit-distance.py +++ b/chapter9/1_edit-distance.py @@ -44,7 +44,8 @@ class Solution: 2. 定义状态:dp[i][j] => word1前i个字符构成的子串与word2前j个字符构成的子串的编辑距离; 3. base case => dp[i][0] = i, dp[0][j] = j => 表示其中一个子串为空的情形 4. 状态转移方程: - f(i, j) = 0 i == 0 || j == 0 + f(i, j) = j i == 0 + i j == 0 f(i - 1, j - 1) i > 0 && j > 0 && word1[i] == word2[j] min { i > 0 && j > 0 && word1[i] != word2[j] f(i - 1, j) + 1, diff --git a/chapter9/2_burst-ballons.py b/chapter9/2_burst-ballons.py index def6545..d17786c 100644 --- a/chapter9/2_burst-ballons.py +++ b/chapter9/2_burst-ballons.py @@ -48,16 +48,14 @@ class Solution: # 在前后各添加一个不能戳破的假气球,其值为1 nums.insert(0, 1) nums.append(1) - + # 初始化dp数组 dp = [[0] * (length + 2) for i in range(length + 2)] - # 从下往上,从左往右遍历 - for i in range(length, -1, -1): - for j in range(i + 2, length + 2): - for k in range(i + 1, j): - dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]) - + for i in range(2, length + 2): + for j in range(0, length + 2 - i): + dp[j][j + i] = max((dp[j][k] + dp[k][j + i] + nums[j] * nums[k] * nums[j + i]) for k in range(j + 1, j + i)) + return dp[0][-1] diff --git a/chapter9/3_my-calendar-i.py b/chapter9/3_my-calendar-i.py index 29c6ff3..e50f3dd 100644 --- a/chapter9/3_my-calendar-i.py +++ b/chapter9/3_my-calendar-i.py @@ -45,7 +45,7 @@ class MyCalendar: (knowledge) 思路: - 1. 用一个数组记录行程安排,其中每个元素为一个二元组,表示左闭又开的行程安排; + 1. 用一个列表记录行程安排,其中每个元素为一个二元组,表示左闭又开的行程安排; 2. 每次插入之前判断当前行程是否与既定行程重叠,重叠则返回False; 3. 如果不重叠,则在适当位置插入行程,保证整体有序; """ diff --git a/chapter9/7_binary-tree-preorder-traversal.py b/chapter9/7_binary-tree-preorder-traversal.py index 52c23ff..270200c 100644 --- a/chapter9/7_binary-tree-preorder-traversal.py +++ b/chapter9/7_binary-tree-preorder-traversal.py @@ -54,3 +54,25 @@ class Solution: result = [] return _preorderTraversal(root, result) + + def preorderTraversal2(self, root): + """ + :type root: TreeNode + :rtype List[int] + + (knowledge) + + 非递归解法 + 思路: + 1. 使用一个列表记录遍历过的值; + 2. 每次访问当前值,并将右左子树入栈; + """ + result, stack = [], [root] + while stack: + node = stack.pop() + if not node: + continue + result.append(node.val) + stack.append(node.right) + stack.append(node.left) + return result