Java Concise O(n) time O(n) space


  • 0
        public int[] nextGreaterElements(int[] nums) {
            int n = nums.length, maxValue = Integer.MIN_VALUE;
            int[] res = new int[n];
            Stack<Integer> stack = new Stack<Integer>();
            for (int i=0;i<n;i++) maxValue = Math.max(nums[i], maxValue);
            for (int i=0;i<2*n;i++) {
                while (!stack.isEmpty() && nums[i % n] > nums[stack.peek()]) 
                    res[stack.pop()] = nums[i % n];
                if (nums[i % n] == maxValue) res[i % n] = -1;
                stack.push(i % n);
            }
            return res;
        }
    

Log in to reply
 

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