Java Solution with HashMap


  • 0

    Since there is no duplicate, we can create a valToIndex map to accelerate lookup for the index we need to start from.

    public class Solution {
        public int[] nextGreaterElement(int[] findNums, int[] nums) {
            
            Map<Integer, Integer> valToIndex = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                valToIndex.put(nums[i], i);
            }
            
            int[] result = new int[findNums.length];
            for (int i = 0; i < findNums.length; i++) {
                result[i] = -1;
                int start = valToIndex.get(findNums[i]);
                
                for (int j = start + 1; j < nums.length; j++) {
                    if (nums[j] > findNums[i]) {
                        result[i] = nums[j];
                        break;
                    }
                }
            }
            
            return result;
        }
    }
    

  • 0
    A

    @shawngao Thank You!


Log in to reply
 

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