单调栈:下一个更大元素
一、面试常考点
1. 为什么用栈
维护“还没找到答案”的下标集合。
2. 维护单调性
当前元素更大时,持续弹栈并结算答案。
二、细节介绍
1. 递减栈
栈内对应值保持递减,方便找下一个更大值。
2. 时间复杂度
每个元素最多入栈出栈一次,总 O(n)。
三、示例代码
function dailyTemperatures(temps) {
const n = temps.length
const ans = Array(n).fill(0)
const stack = []
for (let i = 0; i < n; i++) {
while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
const idx = stack.pop()
ans[idx] = i - idx
}
stack.push(i)
}
return ans
}
四、常用应用场景
1. 时间序列趋势分析
寻找下一次升高/降低时刻。
2. 金融行情处理
最近更高价/更低价定位。