题目

核心思路(单调递减栈)
栈的作用 :存储温度数组的索引,且栈内索引对应的温度值保持单调递减。
遍历逻辑:
- 遍历每个温度时,若当前温度 > 栈顶索引的温度 → 栈顶索引的 "下一个更高温度" 就是当前索引,计算距离并弹出栈顶。
- 重复上述过程直到栈为空 / 当前温度 ≤ 栈顶温度,再将当前索引压入栈。
- 未找到更高温度的元素:栈中剩余索引(右侧无更高温度),结果置 0。
Java代码实现
java
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Deque<Integer> stack = new LinkedList<>();
int n = temperatures.length;
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
int t = temperatures[i];
while (!stack.isEmpty() && t > temperatures[stack.peek()]) {
int idx = stack.pop();
ans[idx] = i - idx;
}
stack.push(i);
}
return ans;
}
}
复杂度分析
- 时间复杂度:O (n)。每个元素仅入栈和出栈一次,总操作次数为 2n。
- 空间复杂度:O (n)。最坏情况下(温度严格递减),栈存储所有索引。