该 readme 用于每天记录 做了哪些题
- https://leetcode-cn.com/problems/combination-sum-ii/
- https://leetcode-cn.com/problems/permutations-ii/submissions/
- https://leetcode.com/problems/subsets-ii/
- https://leetcode-cn.com/problems/combination-sum/submissions/
- https://leetcode-cn.com/problems/number-of-islands/
- https://leetcode-cn.com/problems/number-of-enclaves/
- https://leetcode-cn.com/problems/number-of-islands/
- https://leetcode-cn.com/problems/max-area-of-island/
- https://leetcode-cn.com/problems/count-sub-islands/
- https://leetcode-cn.com/problems/generate-parentheses/
- https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
- leftbound 两种实现,rightbound 的两种实现
- https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
- https://leetcode.cn/problems/binary-search/
- https://leetcode.cn/problems/search-insert-position/
- https://leetcode.cn/problems/merge-k-sorted-lists/submissions/
- https://leetcode.com/problems/merge-two-sorted-lists/
- https://leetcode.cn/problems/remove-nth-node-from-end-of-list/submissions/ 这题记得去好好写模板
- https://leetcode.cn/problems/middle-of-the-linked-list/submissions/ 快慢指针
- https://leetcode.cn/problems/linked-list-cycle/submissions/ 快慢指针
- https://leetcode.cn/problems/linked-list-cycle-ii/submissions/
- https://leetcode.cn/problems/intersection-of-two-linked-lists/
- https://leetcode.cn/problems/reverse-linked-list/ 递归实现反转单链表(模板), 需要背熟
- https://leetcode.cn/problems/reverse-linked-list-ii/ python 的实现不太一样 需要背熟
- https://leetcode.cn/problems/reverse-nodes-in-k-group/submissions/ 用迭代实现反转
- https://leetcode.cn/problems/valid-palindrome/submissions/
- https://leetcode.cn/problems/palindrome-linked-list/submissions/
- https://leetcode.cn/problems/remove-duplicates-from-sorted-array/ 原地修改数组 (快慢)
- https://leetcode.cn/problems/remove-duplicates-from-sorted-list/submissions/ 原地修改链表 (快慢)
- https://leetcode.cn/problems/remove-element/ 原地修改数组 (快慢)
- https://leetcode.cn/problems/move-zeroes/submissions/ 原地修改数组 (快慢)
- https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/submissions/ (两边向中间 move 的指针)
- https://leetcode.cn/problems/reverse-string/submissions/ (两边向中间 move 的指针)
- https://leetcode.cn/problems/longest-palindromic-substring/submissions/ (中间向两边 move 的指针)
- https://leetcode.cn/problems/range-addition/submissions/
- https://leetcode.cn/problems/corporate-flight-bookings/
- https://leetcode.cn/problems/car-pooling/submissions/
- https://leetcode.cn/problems/minimum-window-substring/submissions/
- https://leetcode.cn/problems/permutation-in-string/submissions/
- https://leetcode.com/problems/find-all-anagrams-in-a-string/
- https://leetcode.cn/problems/longest-substring-without-repeating-characters/submissions/
- https://leetcode.cn/problems/capacity-to-ship-packages-within-d-days/solution/-by-sparkk-dni3/
- https://leetcode.cn/problems/koko-eating-bananas/
- https://leetcode.cn/problems/house-robber/submissions/
- https://leetcode.cn/problems/house-robber-ii/submissions/
- https://leetcode.cn/problems/house-robber-iii/submissions/
- https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
- https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
- https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/
- https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/
- https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
- https: // leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/submissions/
June 27 复习 二叉搜索树
- https://leetcode.com/problems/kth-smallest-element-in-a-bst
- https://leetcode.com/problems/convert-bst-to-greater-tree
- https://leetcode.cn/problems/validate-binary-search-tree
- https://leetcode.cn/problems/delete-node-in-a-bst
- https://leetcode.cn/problems/search-in-a-binary-search-tree
- https://leetcode.cn/problems/insert-into-a-binary-search-tree
- https://leetcode.cn/problems/unique-binary-search-trees-ii
- https://leetcode.cn/problems/unique-binary-search-trees 看了一下图
June 28 复习 DP
- https://leetcode.com/problems/add-two-numbers/submissions/
- https://leetcode.cn/problems/fibonacci-number
- https://leetcode.com/problems/coin-change/submissions
- https://leetcode.cn/problems/longest-increasing-subsequence
- https://leetcode.cn/problems/russian-doll-envelopes
- https://leetcode.cn/problems/maximum-subarray
June 29 新做
-
https://leetcode.cn/problems/reorder-list/ 栈 处理链表节点 。我的思路是使用了 dummy 节点 创建新的 list 我还是喜欢我的方法,容易看懂 下面三个很相似
-
https://leetcode.cn/problems/valid-parentheses/ 栈处理 括号 栈是一种先进后出的数据结构,处理括号问题的时候尤其有用。遇到左括号就入栈,遇到右括号就去栈中寻找最近的左括号,看是否匹配。
-
https://leetcode.cn/problems/minimum-add-to-make-parentheses-valid/ 栈处理 括号
-
https://leetcode.cn/problems/evaluate-reverse-polish-notation/ 栈
June 30
-
https://leetcode.cn/problems/implement-queue-using-stacks/ 需要两个 stack。
peek 查看队头的元素怎么办呢?按道理队头元素应该是 1, 但是在 s1 中 1 被压在栈底,现在就要轮到 s2 起到一个中转的作用了: 当 s2 为空时,可以把 s1 的所有元素取出再添加进 s2,这时候 s2 中元素就是先进先出顺序了。 https: // leetcode.cn/problems/implement-stack-using-queues/ -
一个 queue 就行 需要一个 记录栈顶元素(也就队尾元素) push API,直接将元素加入队列,同时记录队尾元素,因为队尾元素相当于栈顶元素,如果要 top 查看栈顶元素的话可以直接返回:
-
底层数据结构是先进先出的队列,每次 pop 只能从队头取元素;但是栈是后进先出,也就是说 pop API 要从队尾取元素.解决方法简单粗暴,把队列前面的都取出来再加入队尾,让之前的队尾元素排到队头,这样就可以取出了.原来的队尾元素被提到队头并删除了,但是 top_elem 变量没有更新.等到在新的队尾元素到对头的时候停止 while 循环,赋值新的 top_element。然后再继续 append https://leetcode.cn/problems/min-stack/ 利用两个栈
def __init__(self):
self.stk = deque()
self.minstk = deque() # 定义很特别从某元素到栈底的最小元素
下面都是 queue 的题目
- https://leetcode.cn/problems/design-hit-counter/
- https://leetcode.cn/problems/number-of-recent-calls/submissions/
- https://leetcode.cn/problems/moving-average-from-data-stream/
- https://leetcode.cn/problems/design-circular-queue/submissions/
July 1st
- https://leetcode.cn/problems/binary-tree-inorder-traversal/
- https://leetcode.cn/problems/binary-tree-postorder-traversal/
- https://leetcode.cn/problems/binary-search-tree-iterator/
- https://leetcode.cn/problems/binary-tree-level-order-traversal/
- https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
- https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/
July 2st
- https://leetcode.cn/problems/recover-binary-search-tree
- https://leetcode.cn/problems/kth-smallest-element-in-a-bst/
- https://leetcode.cn/problems/inorder-successor-in-bst/
- https://leetcode.cn/problems/closest-binary-search-tree-value-ii/
- https://leetcode.cn/problems/binary-tree-paths/
- https://leetcode.cn/problems/closest-binary-search-tree-value/
- https://leetcode.cn/problems/binary-tree-right-side-view/
- https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
- https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree/ 递归
- https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
- https://leetcode.cn/problems/binary-tree-maximum-path-sum/ 这题特别好
July 3st
- 235 https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
- 250 https://leetcode.cn/problems/count-univalue-subtrees/
- 333 https://leetcode.cn/problems/largest-bst-subtree/
- 100 https://leetcode.cn/problems/same-tree 遍历的思路
- 110 https://leetcode.cn/problems/balanced-binary-tree
- 111 https://leetcode.cn/problems/minimum-depth-of-binary-tree/submissions/
- 112 https://leetcode.cn/problems/path-sum
- 113 https://leetcode.cn/problems/path-sum-ii
- 129 https://leetcode.cn/problems/sum-root-to-leaf-numbers/
- 222 https://leetcode.cn/problems/count-complete-tree-nodes/
- 298 https://leetcode.cn/problems/binary-tree-longest-consecutive-sequence/submissions/
- 101 https://leetcode.cn/problems/symmetric-tree/ 这个题目特别好
- 366 https://leetcode.cn/problems/find-leaves-of-binary-tree/ 是一个后序的题目 很有意思
July 4th
- 314 https://leetcode.cn/problems/binary-tree-vertical-order-traversal/ 二叉树的垂直遍历
- 127 https://leetcode.cn/problems/word-ladder/ 单词接龙
July 5th
- 22 https://leetcode.cn/problems/generate-parentheses/ 括号生成
- 17 https://leetcode.cn/problems/letter-combinations-of-a-phone-number/ 电话号码的字母组合
- 39 https://leetcode.cn/problems/combination-sum/ 组合总和
- 40 https://leetcode.cn/problems/combination-sum-ii/ 组和总和 II
- 79 https://leetcode.cn/problems/word-search/ 单词搜索
- 39 https://leetcode.cn/problems/restore-ip-addresses/ 复原 ip 地址
- 5 https://leetcode.cn/problems/longest-palindromic-substring/ 最长回文子串
- 131 https://leetcode.cn/problems/palindrome-partitioning/ 分割回文串 July 6th
- 409 https://leetcode.cn/problems/longest-palindrome/ 最长回文串
- 647 https://leetcode.cn/problems/palindromic-substrings/ 回文子串
- 9 https://leetcode.cn/problems/palindrome-number/ 回文数
- 516 https://leetcode.cn/problems/longest-palindromic-subsequence/ 最长回文子序列
- 60 https://leetcode.cn/problems/permutation-sequence/ 排列序列 烂题
- 139 https://leetcode.cn/problems/word-break/ 单词拆分
- 140 https://leetcode.cn/problems/word-break-ii/ 单词拆分 2
July 13rd
- 226 https://leetcode.cn/problems/palindrome-permutation/
- 242 https://leetcode.cn/problems/valid-anagram/
- 49 https://leetcode.cn/problems/group-anagrams/submissions/ 这个故事告诉我们 string 也可以被 sorted,return value 是一串 list July 14th
- https://leetcode.cn/problems/reverse-integer/solution/ str 或者 list 都可以用 X[::-1]来实现反转
- https://leetcode.cn/problems/group-shifted-strings/ 哈希表
- https://leetcode.cn/problems/jump-game-ii/solution/ dp
- https://leetcode.cn/problems/reorder-data-in-log-files/submissions/ 用完 sorted 要重新赋值,sorted(X,key=itemgetter(0,1))
- https://leetcode.cn/problems/top-k-frequent-elements/ 狠狠的使用 counter
- https://leetcode.cn/problems/find-all-anagrams-in-a-string/ 最简单的一个滑动窗口 July 15th
- https://leetcode.cn/problems/minimum-size-subarray-sum/
- 56 https://leetcode.cn/problems/merge-intervals/ 区间做法,先排序 再俩 if 判断是 包括还是 overlap
- 57 https://leetcode.cn/problems/insert-interval/
- https://leetcode.cn/problems/remove-covered-intervals/submissions/
- https://leetcode.cn/problems/climbing-stairs/ 等价于 fib 斐波那契额数列
16 th https://leetcode.cn/problems/search-in-rotated-sorted-array/ 这是一道好题目 第一题做这个 21st
- 33 https://leetcode.cn/problems/search-in-rotated-sorted-array/
- 80 https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
- 81 https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/
- 23 https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
21st
- 33 https://leetcode.cn/problems/search-in-rotated-sorted-array/
- 80 https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
- 26 https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
- 81 https://leetcode.cn/problems/search-in-rotated-sorted-array-ii/
22nd
- https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array/
- https://leetcode.com/problems/meeting-rooms-ii/ 很奇怪的做法 草
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
start_list=[]
end_list=[]
n=len(intervals)
for i in range(n):
start_list.append(intervals[i][0])
end_list.append(intervals[i][1])
count=0
start_list=sorted(start_list)
end_list=sorted(end_list)
s=e=0
available=numroom=0
while s<len(start_list):
if start_list[s]<end_list[e]:
if available==0:
numroom+=1
else:
available-=1
s+=1
else:
available+=1
e+=1
return numroom
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
freerooms=[]
intervals.sort(key=lambda x:x[0])
print(intervals)
heapq.heappush(freerooms,intervals[0][1])
for i in range(1,len(intervals)):
if freerooms[0]<=intervals[i][0]:
heapq.heappop(freerooms)
heapq.heappush(freerooms,intervals[i][1])
return len(freerooms)
Gonna do following questions https://leetcode.com/company/amazon/
What difference between subarray, subset, and substring? Basically, subarray(substring) has order and continuity, but subset doesn't. For example: nums = [1, 2, 3] The subarray of nums is: [1], [1,2], [1,2,3], [2], [2,3], [3]. The subset of nums is: [1], [1,2], [1,2,3], [2], [2,3], [3], [1,3]. <- The order doesn't matter in subset, so you can write [1,3] or [3,1]. Both of them are the same subset of nums.
When you are writing the subarray, you can think the bracket parenthesis is moving. [1] 2] 3] <- There is one place to put left bracket, and there are three place to put right bracket. So we get [1], [1,2], [1,2,3]. 13 = 3 1 [2] 3] <- There is one place to put left bracket, and there are two place to put right bracket. So we get [2], [2,3]. 12 = 2 1 2 [3] <- There is one place to put left bracket, and there are one place to put right bracket. So we get [3]. 1*1 = 1
Finally, total subarray of nums is 3+2+1 = 6. (formula to reach the total numbe of subarray is n*(n+1)/2)
https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string
index = {c: [-1, -1] for c in ascii_uppercase}
res = 0
for i, c in enumerate(S):
k, j = index[c]
res += (i - j) * (j - k)
index[c] = [j, i]
for c in index:
k, j = index[c]
res += (len(S) - j) * (j - k)
return res % (10**9 + 7)
https://leetcode.com/problems/sum-of-subarray-ranges
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
res=0
for i in range(len(nums)):
max_num=nums[i]
min_num=nums[i]
for j in range(i+1,len(nums)):
max_num=max(max_num,nums[j])
min_num=min(min_num,nums[j])
res+=max_num-min_num
return res
python 自带处理 combination 或者 permutation 的工具 from itertools import combinations
class Solution:
def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:
users=defaultdict(list)
for user,time,site in sorted(zip(username,timestamp,website), key=lambda x: (x[0],x[1])):
users[user].append(site)
patterns=Counter()
for user,sites in users.items():
patterns.update(Counter(set(combinations(sites,3))))
print(sorted(patterns))
return max(sorted(patterns), key=patterns.get)
https://leetcode.com/problems/reorder-data-in-log-files sorted 的 key 可以用来定义 algorithem 返回值一定是 set
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
def sorting_algo(log):
if log[-1].isnumeric():
return (1,)
left_side, right_side=log.split(" ",1)
return (0,right_side,left_side)
return sorted(logs,key=sorting_algo)
https://leetcode.com/problems/sum-of-total-strength-of-wizards/ 前缀和 与单调栈(mono stack),use itertools 的 accumulate 来 build range sum
- https://leetcode.com/problems/search-suggestions-system/submissions/ use str.startwith(str) 很有用 bisect.bisectleft -- https://leetcode.com/problems/search-suggestions-system/discuss/436674/C%2B%2BJavaPython-Sort-and-Binary-Search-the-Prefix 大佬的解法
class Solution:
def suggestedProducts(self, A, word):
A.sort()
res, prefix, i = [], '', 0
for c in word:
prefix += c
i = bisect.bisect_left(A, prefix, i)
print(i)
res.append([w for w in A[i:i + 3] if w.startswith(prefix)])
return res
- https://leetcode.com/problems/k-closest-points-to-origin 这一题就是使用 heapq 22=4 32=9
- https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/ simple two dimensional DP
class Solution:
def getMaxLen(self, nums):
"""
:type nums: List[int]
:rtype: int
dp[i][0] : max length of subarray ending with index i With positive product
dp[i][1] : max length of subarray ending with index i With negative product
"""
n = len(nums)
dp = [[0] * 2 for _ in range(n)]
if nums[0] > 0:
dp[0][0] = 1
if nums[0] < 0:
dp[0][1] = 1
res = dp[0][0]
for i in range(1, n):
cur = nums[i]
if cur > 0:
dp[i][0] = dp[i - 1][0] + 1
if dp[i - 1][1] > 0:
dp[i][1] = dp[i - 1][1] + 1
if cur < 0:
dp[i][1] = dp[i - 1][0] + 1
if dp[i - 1][1] > 0:
dp[i][0] = dp[i - 1][1] + 1
res = max(res, dp[i][0])
return res
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
def reverseN(head, n):
if n == 1:
return head
# 以 head.next 为起点,需要反转前 n - 1 个节点
last = reverseN(head.next, n-1)
successor = head.next.next
# 以head.next为开头的链表已经完成翻转,那么head.next.next正确指向后继节点
head.next.next = head
head.next = successor
return last
fast=head
slow=head
count=0
while fast is not None and fast.next is not None:
count+=1
fast=fast.next.next
slow=slow.next
head=reverseN(head,count)
p2=slow
p1=head
max_num=-(math.inf)
while p2 is not None:
max_num=max(p1.val+p2.val,max_num)
p1=p1.next
p2=p2.next
return max_num
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
return 1 + sum(damage) - min(max(damage), armor)
class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def lca(node):
"""Return lowest common ancestor of start and dest nodes."""
if not node or node.val in (startValue , destValue): return node
left, right = lca(node.left), lca(node.right)
return node if left and right else left or right
root = lca(root) # only this sub-tree matters
ps = pd = ""
stack = [(root, "")]
while stack:
node, path = stack.pop()
if node.val == startValue: ps = path
if node.val == destValue: pd = path
if node.left: stack.append((node.left, path + "L"))
if node.right: stack.append((node.right, path + "R"))
return "U"*len(ps) + pd
August 2nd
- https://leetcode.com/problems/container-with-most-water/
- https://leetcode.com/problems/trapping-rain-water 用空间换了时间
- https://leetcode.com/problems/product-of-array-except-self 妙用 itertools 的 accumulation, list(accumulate(nums, operator.mul))
- https://leetcode.com/problems/continuous-subarray-sum preSum's tech nique.这道题有点想在考数学 preSum with hashmap
import itertools
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
preSum=list(itertools.accumulate(nums))
preSum.insert(0,0)
valtoIndex={}
for i in range(0,len(preSum)):
val=preSum[i]%k
if val not in valtoIndex:
valtoIndex[val]=i
res=0
for j in range(1,len(preSum)):
need=preSum[j]%k
if need in valtoIndex:
if j-valtoIndex[need]>=2:
return True
return False
- https://leetcode.cn/problems/contiguous-array preSum with hashmap # 不怎么考别看了
- https://leetcode.com/problems/subarray-sum-equals-k/ # 这一题有必要看
Aug 3
- https://leetcode.com/problems/maximum-product-subarray Kadane's Approach
class Solution:
def maxProduct(self, nums: List[int]) -> int:
global_max,pre_max,pre_min=nums[0],nums[0],nums[0]
for num in nums[1:]:
cur_min=min(pre_max*num,pre_min*num,num)
cur_max=max(pre_max*num,pre_min*num,num)
global_max=max(cur_max,global_max)
pre_max=cur_max
pre_min=cur_min
return global_max
- https://leetcode.cn/problems/next-permutation/ 并不是一道很有必要的题目
- https://leetcode.com/problems/sort-colors/ # 有点意思 三元素排序
Aug 4th
- https: // leetcode.com/problems/first-missing-positive/ 先 sort 再找
- https://leetcode.com/problems/largest-rectangle-in-histogram/ 单调栈
- https://leetcode.com/problems/course-schedule 构件图 判断是否有环
August 5 th