題目出處
難度
Medium
個人範例程式碼
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
if not temperatures:
return []
stack = []
ans = [0 for _ in range(len(temperatures))]
for today, temperature in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temperature: # today's temperature is higher
idx = stack.pop(-1)
ans[idx] = today - idx
stack.append(today)
return ans
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
算法說明
stack 的經典題型,透過 stack 紀錄沿路上的過去史,
並不斷地以「今日」去比對「過去尚未產生結果的結果」
- pop 至過去結果溫度「比今日小的所有結果」,相距日期則為「today – 該日」
input handling
如果沒有 input,return []
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 | ||
⭐ Binary Serach 相關題型 ⭐ | ||||||
33 | Search in Rotated Sorted Array | Binary Serach | Array | Python | #重要題型 | |
34 | Find First and Last Position of Element in Sorted Array | Binary Serach | Python | |||
50 |