07/19/2022
1) 158. Read N Characters Given read4 II - Call Multiple Times (Hard)
注意提供的read4(buf4)函数
2) 735. Asteroid Collision
思路: 注意只有正+负会相遇,负+正是反方向不相遇。区分几种情况,正大负小,一样大,正小负大。用Stack存储,消除就pop。
3) 716. Max Stack (Hard)
思路:
- 用list模拟stack
- Double Linked List + TreeMap
4) 238. Product of Array Except Self
思路: 记录0的数量,和非0的其他所有数的乘积,分类讨论
5) 642. Design Search Autocomplete System (Hard)
思路:
- 存按热度和alphabete排序的history,以及热度dict,每次遇到#就进行更新
- Trie
6) 365. Water and Jug Problem
思路:
math方法,key idea是结果是x和y的线性组合(因为每一步操作都是x和y的线性组合,所以不管进行了多少步,仍然是x和y的线性组合,且每一步都是当前值的0或1倍,所以每种取值都是有可能的,只要0<=ax+by<=x+y)
根据Bézout's identity,ax+by=m有整数解时当且仅当m是a及b的最大公约数d(greatest common divisor,gcd)的倍数。
求最大公约数的方法是,用较小数除较大数,再用出现的余数(第一余数)去除除数,再用出现的余数(第二余数)去除第一余数,如此反复,直到最后余数是0为止。def computeGCD(x, y): while(y): x, y = y, x % y return abs(x)
- BFS Breadth-first search
每一步都有6个可能性
Pour contents of jug1 to jug2. (note that jug1 may still have some water left after pouring water to jug2)
Pour contents of jug2 to jug1. (note that jug2 may still have some water left after pouring water to jug1)
Empty jug1 completely.
Empty jug2 completely.
Fill jug1 completely (to its maximum limit)
Fill jug2 completely (to its maximum limit)
遍历这6种可能性,每一种可能性下一步又能衍生出6种可能性
直到等于target,或者ax+by的(a,b)出现循环(有限种,因为0<value<x+y)
7) 981. Time Based Key-Value Store
思路: 用dictionary和list的组合存储key-value-timestamp的信息,用二分法搜索pre_timestamp
8) 127. Word Ladder (Hard)
思路: BFS, 用all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)存储每个generic word的可能性,level记录步数,先找到所有level=1能到达的,再找level=2能到达的,并用visited确保不重复,直到找到endword或者所有路径都被遍历return0
9) 126. Word Ladder II (Hard)
BFS layer by layer
和127类似,但是要存储路径
10) 304. Range Sum Query 2D - Immutable
brute force会超时,要cache
思路:
1.Caching Rows
2.Caching Smarter
始终以(0,0)为起点
Sum(ABCD)=Sum(OD)−Sum(OB)−Sum(OC)+Sum(OA)
11) 76. Minimum Window Substring (Hard)
- Use two pointers: start and end to represent a window.
- Move end to find a valid window.
- When a valid window is found, move start to find a smaller window.
- if smaller window not including all chars, move end pointer to find the next desired window.
template for substring questions:
class Solution(object):
def min_window(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
# Idea: Two pointers: moving end forward to find a valid window,
# moving start forward to find a smaller window
# counter and hash_map to determine if the window is valid or not
# Count the frequencies for chars in t
hash_map = dict()
for c in t:
if c in hash_map:
hash_map[c] += 1
else:
hash_map[c] = 1
start, end = 0, 0
# If the minimal length doesn't change, it means there's no valid window
min_window_length = len(s) + 1
# Start point of the minimal window
min_window_start = 0
# Works as a counter of how many chars still need to be included in a window
num_of_chars_to_be_included = len(t)
while end < len(s):
# If the current char is desired
if s[end] in hash_map:
# Then we decreased the counter, if this char is a "must-have" now, in a sense of critical value
if hash_map[s[end]] > 0:
num_of_chars_to_be_included -= 1
# And we decrease the hash_map value
hash_map[s[end]] -= 1
# If the current window has all the desired chars
while num_of_chars_to_be_included == 0:
# See if this window is smaller
if end - start + 1 < min_window_length:
min_window_length = end - start + 1
min_window_start = start
# if s[start] is desired, we need to update the hash_map value and the counter
if s[start] in hash_map:
hash_map[s[start]] += 1
# Still, update the counter only if the current char is "critical"
if hash_map[s[start]] > 0:
num_of_chars_to_be_included += 1
# Move start forward to find a smaller window
start += 1
# Move end forward to find another valid window
end += 1
if min_window_length == len(s) + 1:
return ""
else:
return s[min_window_start:min_window_start + min_window_length]
08/14/2022
12) 91. Decode Ways
Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
思路:
1.Recursive,但是尝试了不加@lru_cache(maxsize=None)会超时?
2.Iterative, dynamic programming, dp = [0 for _ in range(len(s) + 1)]存储subproblem results,每次检验1 digit和2 digit可能性
13) 200. Number of Islands
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
思路:
遍历,遇到1就count+=1并进行DFS,把与它相连的1全部变成别的符号例如#,表示已经数过。再去找下一个没有变成#的1(新的岛)
14) 426. Convert Binary Search Tree to Sorted Doubly Linked List
Input: root = [4,2,5,1,3]
Output: [1,2,3,4,5]
思路: Recursive, DFS. 定义first和last变量,先到最左找到first,回到上个node互相相连,以此类推,直到最右last,再将first和last相连。
def treeToDoublyList(self, root: 'Node') -> 'Node':
if not root:
return None
first, last = None, None
def helper(node):
nonlocal first, last
if node:
helper(node.left)
if last:
last.right = node
node.left = last
else:
first = node
last = node
helper(node.right)
helper(root)
last.right = first
first.left = last
return first
15) 144. Binary Tree Preorder Traversal
Pre-order, NLR
Visit the current node .
Recursively traverse the current node's left subtree.
Recursively traverse the current node's right subtree.
Input: root = [1,null,2,3]
Output: [1,2,3]
思路:
1.recursive
2.iterative,每到一个节点都用stack存root,遍历左边,再不断pop stack
16) 1028. Recover a Tree From Preorder Traversal (Hard)
iterative,每到一个节点都用stack存root,遍历左边,再不断pop stack
17) 208. Implement Trie (Prefix Tree)
前缀树,又称字典树。它是一棵 N 叉树。前缀树用于存储、查找字符串。前缀树的每一个结点代表一个字符串的前缀。每一个结点会有多个子结点,通往不同子结点的路径上有着不同的字符。子结点代表的字符串是由结点本身的原始字符串 ,以及通往该子结点路径上所有的字符组成的。
前缀树的一个重要的特性是,结点所有的后代都与该结点相关的字符串有着共同的前缀,这是前缀树名称的由来。
没看懂答案。
18) 114. Flatten Binary Tree to Linked List
注意是in place修改
def __init__(self):
self.prev = None
def flatten(self, root):
if not root:
return None
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
root.left = None
self.prev = root
18) 22. Generate Parentheses
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
思路:
1.Brute Force会超时
2.Backtracking. Instead of adding '(' or ')' every time as in Approach 1, let's only add them when we know it will remain a valid sequence. We can do this by keeping track of the number of opening and closing brackets we have placed so far.
3.Closure Number. The problem can be reduced to two separate subproblems. One is about parentheses inside these brackets and another is about parentheses to the right.
19) 210. Course Schedule II
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
思路:
1.Depth First Search
2.Node Indegree 没看懂
20) 98. Validate Binary Search Tree
determine if it is a valid binary search tree (BST).
思路:
1.Recursive Traversal with Valid Range
2.Iterative Traversal
3.Recursive Inorder Traversal
4.Iterative Inorder Traversal
21) 3. Longest Substring Without Repeating Characters
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
思路:Sliding Window
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。