[JAVA] Use stack and save index with twice loop / T : O(N), S : O(N)


  • 0
    J
    class Solution {
        public int[] nextGreaterElements(int[] nums) {
            int[] result = new int[nums.length];
            if(nums.length == 0)
                return result;
            
            Stack<Integer> st = new Stack<Integer>();
            for(int i = 0; i < nums.length; i++)
                result[i] = -1;        
            for(int i = 0; i < nums.length*2; i++){
                while(!st.isEmpty() && (nums[st.peek()] < nums[i%nums.length])){
                    result[st.pop()] = nums[i%nums.length];
                }
                
                if(i < nums.length){
                    st.push(i);    
                }
                
            }
            
            
            return result;
        }
    }
    

Log in to reply
 

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