Skip to content

下一个元素

一般用单调栈
单调栈可以在 1 次比较中处理前面的元素和后面的元素

下一个特定元素

503. 下一个更大元素 II mid

给定一个循环数组 nums(nums[nums.length - 1] 的下一个元素是 nums[0]),返回 nums 中每个元素的 下一个更大元素。

数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。

解法 单调栈

java
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        Arrays.fill(res, -1);
        Deque<Integer> stack = new LinkedList<>();
        // 循环数组的时候这样处理
        for (int i = 0; i < n * 2; i++) {
            int idx = i % n;
            while (!stack.isEmpty() && nums[stack.peek()] < nums[idx]) {
                res[stack.pop()] = nums[idx];
            }
            stack.push(idx);
        }
        return res;
    }
}

739. 每日温度 mid

LCR 038. 每日温度

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

java
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        Deque<Integer> stack = new ArrayDeque<>();
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
                int idx = stack.remove();
                res[idx] = i - idx;
            }
            stack.push(i);
        }
        return res;
    }
}