Next Greater Element II


  • 0

    Click here to see the full article post


  • 1

    I think first adding all element indices to stack is easier to understand for me.

        public int[] nextGreaterElements(int[] nums) {
           int n = nums.length;
            Stack<Integer> stack = new Stack();
            for(int i = n - 1; i >= 0; i--){
              stack.push(i);   
            }
            
            int[] res = new int[n];
            for(int i = n - 1; i >= 0; i--){
                res[i] = -1;
                while(!stack.isEmpty() && nums[stack.peek()] <= nums[i]){
                  stack.pop();  
                }
                
                if(!stack.isEmpty()) res[i] = nums[stack.peek()];
                stack.push(i);
            }
            return res;
        }

  • 0

    It means for the right most side elements, first trying to find next greater element from left beginning. The same time adding right elements to stack for elements on its left.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.