Two Stack one pass solution


  • 0

    '''
    class Solution {
    public int[] nextGreaterElements(int[] nums) {
    Stack<Integer> stack = new Stack();
    Stack<Integer> s = new Stack();
    HashMap<Integer, Integer> map = new HashMap();
    int index = 0;
    int cnt = 0;
    int limit = nums.length * 2 - 1;
    int[] res = new int[nums.length];

        while(cnt < limit)
        {
            while(!stack.isEmpty() && nums[cnt%nums.length] > stack.peek())
            {
                stack.pop();
                res[s.pop()] = nums[cnt%nums.length];
            }
            
            if (index < nums.length)
            {
                 stack.push(nums[index]);
                 s.push(index);
                 index++;
            }   
            
            cnt++;            
        }
        
        while(!stack.isEmpty())
        {
            stack.pop();
            res[s.pop()] = -1;
        }
        
        
        return res;
        
    }
    

    }
    '''


Log in to reply
 

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