Java 2-Pass solution using stack


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

Log in to reply
 

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