Original link: https://leetcode.com/problems/daily-temperatures/
Given a list of daily temperatures, return a list such that tell how many days you would have to wait until a warmer temperature.
Initialize a stack (list) to store position.
Iterate the array T in the reverse sequence, the stack will pop out position where the temperature (T[stack[-1]) is less than the current temperature (T[i]).
The remained last element in stack is the position where the temperature is larger than the current one. If the stack is empty, it means that elements after the current one are all smaller.
Code:
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0 for i in range(len(T))]
stack = []
for i in range(len(T)-1, -1, -1):
while stack and T[stack[-1]] <= T[i]:
stack.pop()
if stack:
ans[i] = stack[-1] - i
stack.append(i)
return ans
本文针对LeetCode上的一道题目——每日气温问题进行了解析,介绍了一种利用栈来求解的方法。具体步骤包括初始化一个栈来存储位置,逆序遍历温度数组,并通过比较栈顶元素与当前元素的大小来确定答案。
1143

被折叠的 条评论
为什么被折叠?



