给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指在第 i 天之后,才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
题目来源:力扣(LeetCode)
题目链接:https://leetcode.cn/problems/daily-temperatures
实现思路:使用栈,如果栈为空当前温度idx入栈,如果不为空,比较栈顶数据对应的温度是否小于当前温度,如果当前温度大,则满足条件栈顶内容出栈,出栈值与当前温度idx值相减即为出栈idx对应温度的返回值。并继续比较新的栈顶对应温度与当前温度,直到当前温度小于栈顶对应温度,并将当前温度idx入栈。
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
sta=[]
ret=[0]*len(temperatures)
i=0
for t in temperatures:
while len(sta)>0 and i >0:
if t >temperatures[sta[-1]]:
n=sta.pop()
ret[n]=i-n
else:
break
sta.append(i)
i+=1
return ret