Using stack, two pass:

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> stk = new Stack<>();
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);
        stk.push(0);
        for(int i=1;i<nums.length;i++){
            while(!stk.isEmpty() && nums[i]>nums[stk.peek()]){
                res[stk.pop()]=nums[i];
            }
            stk.push(i);
        }
        for(int i=0;i<nums.length;i++){
            while(!stk.isEmpty() && nums[i]>nums[stk.peek()]){
                res[stk.pop()]=nums[i];
            }
            stk.push(i);
        }
        return res;
    }
}

 

posted on 2022-04-20 11:11  阳光明媚的菲越  阅读(14)  评论(0编辑  收藏  举报