題目:
根據(jù)每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度才會升高超過該日的天數(shù)。如果之后都不會升高,請在該位置用 0 來代替。
例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:氣溫 列表長度的范圍是 [1, 30000]。每個氣溫的值的均為華氏度,都是在 [30, 100] 范圍內(nèi)的整數(shù)。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/daily-temperatures
著作權歸領扣網(wǎng)絡所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權,非商業(yè)轉(zhuǎn)載請注明出處。
解題思路
使用遞減棧的概念,詳見鏈接:
http://www.itdecent.cn/p/6bbd3653a57f
遍歷數(shù)組,當元素比棧中元素都小都時候壓棧(下標和數(shù)值),否則把比元素小的都彈棧。
代碼
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
output = [0] * len(T)
for i in range(len(T)):
while len(stack) > 0 and T[i] > stack[-1][1]:
index, _ = stack.pop()
output[index] = i - index
stack.append((i, T[i]))
return output