Simple Java 8 lines O(n) solution

  • 0

    Push all the numbers to stack first.

    public class Solution {
        public int[] nextGreaterElements(int[] nums) {
            Stack<Integer> s = new Stack<>();
            int[] res = new int[nums.length];
            for(int i = nums.length-1; i>=0; i--) s.push(nums[i]);
            for(int i = nums.length-1; i>=0; i--){
                while(!s.isEmpty() && s.peek() <= nums[i])   s.pop();
                res[i] = s.isEmpty()?-1:s.peek();
            return res;

Log in to reply

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