Monotonic stack solves the next larger element of the circular array

Insert picture description here

class Solution {
    
    
    public int[] nextGreaterElements(int[] nums) {
    
    
        Stack<Integer> stack=new Stack<>();
        int n=nums.length;
        int[] res=new int[n];
        for(int i=2*n-1;i>=0;i--){
    
    
            while(!stack.empty()&&nums[i%n]>=stack.peek()){
    
    
                stack.pop();
            }
           
            res[i%n]=stack.empty()? -1:stack.peek();
             stack.push(nums[i%n]);
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/115267347