O(m+n) solution :9ms


  • 0
    S
    public int[] nextGreaterElement(int[] findNums, int[] nums) {
     Map<Integer,Integer> map = new HashMap<Integer,Integer>();
     int[] stack=new int[nums.length]; int top=-1;
     for(int val:nums){
        while(top!=-1&&val>stack[top]){map.put(stack[top--],val);}
        stack[++top]=val;
     }
     for(int i=0;i<findNums.length;i++){
         if(map.containsKey( findNums[i])){findNums[i]=map.get( findNums[i]);}
         else{findNums[i]=-1;}
     }
     return findNums; }
    

Log in to reply
 

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