8ms: easy to understand, Java solution


  • 0
    S
    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            HashMap<Integer, Integer> numsHash = new HashMap<Integer, Integer>();        
            for (int i=0; i<nums.length; i++){     //populating hashmap
                numsHash.put(nums[i],i);       
            }
            
            int[] retArray = new int[findNums.length];
            for (int i=0; i<findNums.length; i++){
                retArray[i] = -1;
                    // checking if that number exists in the hashmap & is within the array size
                    for (int j=(numsHash.get(findNums[i]) != null)? numsHash.get(findNums[i])+1 : nums.length; j<nums.length; j++){
                        if (nums[j] > findNums[i]){
                            retArray[i] = nums[j];
                            break;
                        }                    
                    }
                }
            return retArray;
            }
        }
    

Log in to reply
 

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