題目出處
難度
easy
個人範例程式碼
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans_hashtable = {}
stack = []
for num in nums2:
while stack and stack[-1] < num: # new is greater
ans_hashtable[stack[-1]] = num # last number's answer = this num
del stack[-1]
stack.append(num)
for rest_element in stack:
ans_hashtable[rest_element] = -1
return [ans_hashtable[num] for num in nums1]
算法說明
像這類有「找後續/前綴」中比較大或比較小的第一個數字,
我們通常會用 stack 來保存「等待被決定的內容」。
當我們發現「stack[-1]」<「新的數字」,表示找到答案,
我們 pop[-1] 出 stack,並記錄「 pop 的答案就是當前數字 」。
最後剩下在 stack 的內容,答案都是 -1
input handling
如果沒有 nums, 回傳 [] (題目沒特別要求)
Boundary conditions
用 for 迴圈控制範圍
Reference
⭐ Leetcode 解題紀錄 ⭐ | 題型 | 資料結構 | Python Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 | Shortest Path in Binary Matrix | BFS (最短路徑) | Matrix | Python | ||