LeetCode 739. 每日溫度
難度中等
請根據每日 氣溫
列表,重新生成一個列表。對應位置的輸出爲:要想觀測到更高的氣溫,至少需要等待的天數。如果氣溫在這之後都不會升高,請在該位置用 0
來代替。
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
length = len(T)
stack = []
ans = [0] * length
for i in range(length):
while stack and T[i] > T[stack[-1]]:
# 棧中有元素, 並且當前元素大於棧頂爲索引的元素,
# 則將該索引彈出, 並且計算該索引和當前索引的距離作爲結果
pre_index = stack.pop()
ans[pre_index] = i - pre_index
stack.append(i)
return ans
注意, stack中存儲的是索引