LeetCode503(2021.3.6)

LC503. 下一个更大元素II

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        Deque<Integer> stack = new LinkedList<Integer>(); //单调递增栈
        int[] res = new int[n];
        Arrays.fill(res, -1);
        for (int i = 0; i < n * 2 - 1; ++i) {
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i % n]) {
                res[stack.pop()] = nums[i % n];
            }
            stack.push(i % n);
        }
        return res;
    }
}

发表评论