503 Next greater element II

https://leetcode.com/problems/next-greater-element-ii/

看右侧的话要在pop时才知道,左侧在插入时就知道了,注意这个circular,挺没意思的

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = -1;
        }
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < 2*n; i++) {
            int cur = i % n;
            if (stack.isEmpty() || nums[stack.peek()] >= nums[cur]) {
                stack.push(cur);
            } else {
                while (!stack.isEmpty() && nums[stack.peek()] < nums[cur]) {
                    int idx = stack.pop();
                    ans[idx] = nums[cur];
                } 
                stack.push(cur);
            }
        }
        return ans;
    }
}

Last updated