单调栈

54 阅读1分钟

模板

单调栈作用:

  1. 单调递减栈,当弹出时可以求得对于弹出元素的下一个更高元素
  2. 单调递增栈

算法

  • 对于每一位,如果栈不为空,且当前数字大于栈内数字,则弹出处理,处理完入栈。
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int cur = stack.pop();
                int diff = i - cur;
                res[cur] = diff;
            }
            stack.push(i);
        }
        return res;
    }
}