503.Next Greater Element II

1-Stack

Two Pass

https://leetcode.com/problems/next-greater-element-ii/discuss/98273/

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;;
        int[] ans = new int[n];
        Arrays.fill(ans, -1);
        //Index Stack
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i = 0; i < n; i++){
            int num = nums[i];
            while(!stack.isEmpty() && nums[stack.peek()] < num){
                ans[stack.pop()] = num;
            }
            stack.push(i);
        }
        //Handle the remain part
        for(int i = 0; i < n; i++){
            int num = nums[i];
            while(!stack.isEmpty() && nums[stack.peek()] < num){
                ans[stack.pop()] = num;
            }
        }
        return ans;
    }
}

results matching ""

    No results matching ""