法1:单调栈
必须掌握算法,关于单调栈、单调队列和环形队列相关参见《算法小抄》相关内容。
类似题目:下一个更大的元素
Python
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
stack = []
res = [0] * n
for i in range(n-1, -1, -1):
cur = temperatures[i]
while stack and temperatures[stack[-1]] <= cur:
stack.pop()
res[i] = stack[-1] - i if stack else 0
stack.append(i)
return res
Java
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
Stack<Integer> s = new Stack<>();
for (int i = n - 1; i >= 0; --i) {
while (!s.isEmpty() && temperatures[s.peek()] <= temperatures[i]) {
s.pop();
}
res[i] = s.isEmpty() ? 0 : s.peek() - i;
s.push(i);
}
return res;
}
}
文章介绍了如何使用单调栈解决`dailyTemperatures`问题,通过遍历温度数组,维护一个栈来跟踪满足条件的先前温度,计算每个温度升高到当前温度所需的天数。
817

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



