for num in nums: #遍历当前的数据 if stack isNoneor stack[0] >= target:# 如果栈为空或者栈顶元素大于等于当前的比较元素 stack.append(num) # 入栈,主要是用来更新stack else: while stack isnotNoneand stack[0] < target: # 当栈不为空并且栈顶元素小于当前比较元素 stack.pop() # 栈顶元素出栈 pass# 更新结果 stack.append(num)# 当前数据入栈
defdailyTemperatures(temperatures:List[int]) -> List[int]: n = len(temperatures) res = [0] * n stack = [0] for i inrange(1, n): if temperatures[i] < temperatures[stack[-1]]: # 更新stack stack.append(i) elif temperatures[i] == temperatures[stack[-1]]: # 更新stack stack.append(i) else: while stack and temperatures[i] > temperatures[stack[-1]]: # while 持续循环弹出栈顶元素,并使用res记录结果 res[stack[-1]] = i - stack[-1] stack.pop() stack.append(i) return res