@@ -40,6 +40,41 @@ class MinStack:
4040 return self .stack[- 1 ][1 ]
4141```
4242
43+ ``` Python
44+ class MinStack :
45+
46+ def __init__ (self ):
47+ """
48+ initialize your data structure here.
49+ """
50+ self .stack = []
51+
52+
53+ def push (self , val : int ) -> None :
54+ if self .stack:
55+ self .stack.append([val, min (val, self .stack[- 1 ][1 ])])
56+ else :
57+ self .stack.append([val, val])
58+
59+ def pop (self ) -> None :
60+ self .stack.pop()[0 ]
61+
62+ def top (self ) -> int :
63+ return self .stack[- 1 ][0 ]
64+
65+ def getMin (self ) -> int :
66+ return self .stack[- 1 ][1 ]
67+
68+
69+
70+ # Your MinStack object will be instantiated and called as such:
71+ # obj = MinStack()
72+ # obj.push(val)
73+ # obj.pop()
74+ # param_3 = obj.top()
75+ # param_4 = obj.getMin()
76+ ```
77+
4378### [ evaluate-reverse-polish-notation] ( https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/ )
4479
4580> ** 波兰表达式计算** > ** 输入:** [ "2", "1", "+", "3", "* "] > ** 输出:** 9
@@ -78,6 +113,24 @@ class Solution:
78113 return stack[0 ]
79114```
80115
116+ ``` Python
117+ class Solution :
118+ def evalRPN (self , tokens : List[str ]) -> int :
119+ stack = []
120+ s = [" +" , " -" , " *" , " /" ]
121+ for t in tokens:
122+ if t == s[0 ]:
123+ t = stack.pop(- 2 ) + stack.pop()
124+ elif t == s[1 ]:
125+ t = stack.pop(- 2 ) - stack.pop()
126+ elif t == s[2 ]:
127+ t = stack.pop(- 2 ) * stack.pop()
128+ elif t == s[3 ]:
129+ t = stack.pop(- 2 ) / stack.pop()
130+ stack.append(int (t))
131+ return stack[0 ]
132+ ```
133+
81134### [ decode-string] ( https://leetcode-cn.com/problems/decode-string/ )
82135
83136> 给定一个经过编码的字符串,返回它解码后的字符串。
@@ -111,6 +164,29 @@ class Solution:
111164 return stack_str[0 ]
112165```
113166
167+ ``` Python
168+ class Solution :
169+ def decodeString (self , s : str ) -> str :
170+ num = 0
171+ output = " "
172+ char_stack = [" " ]
173+ num_stack = []
174+ for i in s:
175+ if i >= " 0" and i <= " 9" :
176+ num = num * 10 + int (i)
177+ elif i == " [" :
178+ num_stack.append(num)
179+ char_stack.append(" " )
180+ num = 0
181+ elif i == " ]" :
182+ new = char_stack.pop() * num_stack.pop()
183+ char_stack[- 1 ] += new
184+ else :
185+ char_stack[- 1 ] += i
186+ return char_stack[0 ]
187+ ```
188+
189+
114190### [ binary-tree-inorder-traversal] ( https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ )
115191
116192> 给定一个二叉树,返回它的* 中序* 遍历。
@@ -136,6 +212,23 @@ class Solution:
136212 return inorder
137213```
138214
215+
216+ ``` Python
217+ class Solution :
218+ def inorderTraversal (self , root : TreeNode) -> List[int ]:
219+ result = []
220+ stack = []
221+ while root or stack:
222+ while root:
223+ stack.append(root)
224+ root = root.left
225+ root = stack.pop()
226+ result.append(root.val)
227+ root = root.right
228+ return result
229+ ```
230+
231+
139232### [ clone-graph] ( https://leetcode-cn.com/problems/clone-graph/ )
140233
141234> 给你无向连通图中一个节点的引用,请你返回该图的深拷贝(克隆)。
@@ -194,6 +287,31 @@ class Solution:
194287 return visited[start]
195288```
196289
290+ ``` Python
291+ """
292+ # Definition for a Node.
293+ class Node:
294+ def __init__(self, val = 0, neighbors = None):
295+ self.val = val
296+ self.neighbors = neighbors if neighbors is not None else []
297+ """
298+
299+ class Solution :
300+ def cloneGraph (self , node : ' Node' ) -> ' Node' :
301+ if not node:
302+ return None
303+ deque = collections.deque([node])
304+ output = {node: Node(node.val, [])}
305+ while deque:
306+ cur = deque.popleft()
307+ for nb in cur.neighbors:
308+ if nb not in output:
309+ output[nb] = Node(nb.val, [])
310+ deque.append(nb)
311+ output[cur].neighbors.append(output[nb])
312+ return output[node]
313+ ```
314+
197315### [ number-of-islands] ( https://leetcode-cn.com/problems/number-of-islands/ )
198316
199317> 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
@@ -238,6 +356,31 @@ class Solution:
238356 return num_island
239357```
240358
359+ ``` Python
360+ class Solution :
361+ def numIslands (self , grid : List[List[str ]]) -> int :
362+ num = 0
363+ m_len = len (grid)
364+ n_len = len (grid[0 ])
365+ lst = [- 1 , 0 , 1 , 0 , - 1 ]
366+
367+ def updateGrid (m , n ):
368+ if grid[m][n] == " 1" :
369+ grid[m][n] = " 0"
370+ for i in range (len (lst)- 1 ):
371+ new_m = m + lst[i]
372+ new_n = n + lst[i+ 1 ]
373+ if 0 <= new_m < m_len and 0 <= new_n < n_len:
374+ updateGrid(new_m, new_n)
375+
376+ for m in range (m_len):
377+ for n in range (n_len):
378+ if grid[m][n] == " 1" :
379+ num += 1
380+ updateGrid(m, n)
381+ return num
382+ ```
383+
241384### [ largest-rectangle-in-histogram] ( https://leetcode-cn.com/problems/largest-rectangle-in-histogram/ )
242385
243386> 给定 _ n_ 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
@@ -323,6 +466,21 @@ class Solution:
323466 return max_area
324467```
325468
469+ ``` Python
470+ class Solution :
471+ def largestRectangleArea (self , heights : List[int ]) -> int :
472+ heights.append(0 )
473+ output = 0
474+ stack = [- 1 ]
475+ for i in range (len (heights)):
476+ while len (stack) > 1 and heights[stack[- 1 ]] > heights[i]:
477+ h = stack.pop()
478+ output = max (output, heights[h]* (i- stack[- 1 ]- 1 ))
479+ stack.append(i)
480+ return output
481+ ```
482+
483+
326484## Queue 队列
327485
328486常用于 BFS 宽度优先搜索
@@ -370,6 +528,53 @@ class MyQueue:
370528 return len (self .cache) == 0 and len (self .out) == 0
371529```
372530
531+ ``` Python
532+ class MyQueue :
533+
534+ def __init__ (self ):
535+ """
536+ Initialize your data structure here.
537+ """
538+ self .queue = collections.deque([])
539+
540+ def push (self , x : int ) -> None :
541+ """
542+ Push element x to the back of queue.
543+ """
544+ self .queue.append(x)
545+
546+ def pop (self ) -> int :
547+ """
548+ Removes the element from in front of queue and returns that element.
549+ """
550+ return self .queue.popleft()
551+
552+ def peek (self ) -> int :
553+ """
554+ Get the front element.
555+ """
556+ return self .queue[0 ]
557+
558+ def empty (self ) -> bool :
559+ """
560+ Returns whether the queue is empty.
561+ """
562+ if self .queue:
563+ return False
564+ else :
565+ return True
566+
567+
568+
569+ # Your MyQueue object will be instantiated and called as such:
570+ # obj = MyQueue()
571+ # obj.push(x)
572+ # param_2 = obj.pop()
573+ # param_3 = obj.peek()
574+ # param_4 = obj.empty()
575+ ```
576+
577+
373578### [ binary-tree-level-order-traversal] ( https://leetcode-cn.com/problems/binary-tree-level-order-traversal/ )
374579
375580> 二叉树的层序遍历
@@ -400,6 +605,27 @@ class Solution:
400605 return levels
401606```
402607
608+ ``` Python
609+ class Solution :
610+ def levelOrder (self , root : TreeNode) -> List[List[int ]]:
611+ result = []
612+ if not root:
613+ return result
614+ stack = collections.deque([root])
615+ while stack:
616+ length = len (stack)
617+ result.append([])
618+ for _ in range (length):
619+ root = stack.popleft()
620+ result[- 1 ].append(root.val)
621+ if root.left:
622+ stack.append(root.left)
623+ if root.right:
624+ stack.append(root.right)
625+ return result
626+ ```
627+
628+
403629### [ 01-matrix] ( https://leetcode-cn.com/problems/01-matrix/ )
404630
405631> 给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
@@ -471,6 +697,36 @@ class Solution:
471697 return dist
472698```
473699
700+ ``` Python
701+ class Solution :
702+ def updateMatrix (self , mat : List[List[int ]]) -> List[List[int ]]:
703+ if len (mat) == 0 or len (mat[0 ]) == 0 :
704+ return mat
705+
706+ m, n = len (mat), len (mat[0 ])
707+ dist = [[float (' inf' )] * n for _ in range (m)]
708+
709+ bfs = collections.deque([])
710+ for i in range (m):
711+ for j in range (n):
712+ if mat[i][j] == 0 :
713+ dist[i][j] = 0
714+ bfs.append((i, j))
715+
716+ neighbors = [(- 1 , 0 ), (1 , 0 ), (0 , - 1 ), (0 , 1 )]
717+ while len (bfs) > 0 :
718+ i, j = bfs.popleft()
719+ for dn_i, dn_j in neighbors:
720+ n_i, n_j = i + dn_i, j + dn_j
721+ if n_i >= 0 and n_i < m and n_j >= 0 and n_j < n:
722+ if dist[n_i][n_j] > dist[i][j] + 1 :
723+ dist[n_i][n_j] = dist[i][j] + 1
724+ bfs.append((n_i, n_j))
725+
726+ return dist
727+ ```
728+
729+
474730## 补充:单调栈
475731
476732顾名思义,单调栈即是栈中元素有单调性的栈,典型应用为用线性的时间复杂度找左右两侧第一个大于/小于当前元素的位置。
@@ -491,6 +747,21 @@ class Solution:
491747 return result
492748```
493749
750+ ``` Python
751+ class Solution :
752+ def largestRectangleArea (self , heights : List[int ]) -> int :
753+ heights.append(0 )
754+ output = 0
755+ stack = [- 1 ]
756+ for i in range (len (heights)):
757+ while len (stack) > 1 and heights[stack[- 1 ]] > heights[i]:
758+ h = stack.pop()
759+ output = max (output, heights[h]* (i- stack[- 1 ]- 1 ))
760+ stack.append(i)
761+ return output
762+ ```
763+
764+
494765### [ trapping-rain-water] ( https://leetcode-cn.com/problems/trapping-rain-water/ )
495766
496767``` Python
@@ -511,6 +782,11 @@ class Solution:
511782 return result
512783```
513784
785+ ``` Python
786+
787+ ```
788+
789+
514790## 补充:单调队列
515791
516792单调栈的拓展,可以从数组头 pop 出旧元素,典型应用是以线性时间获得区间最大/最小值。
@@ -549,6 +825,11 @@ class Solution:
549825 return result
550826```
551827
828+ ``` Python
829+
830+ ```
831+
832+
552833### [ shortest-subarray-with-sum-at-least-k] ( https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k/ )
553834
554835``` Python
@@ -575,6 +856,10 @@ class Solution:
575856 return result if result < N + 1 else - 1
576857```
577858
859+ ``` Python
860+
861+ ```
862+
578863## 总结
579864
580865- 熟悉栈的使用场景
0 commit comments