Java solution - beats ~90%


  • 0
    H
    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            HashMap<Integer, Integer> index = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums2.length; i++) {
                index.put(nums2[i], i);
            }
            int[]res = new int[nums1.length];
            for (int i = 0; i < nums1.length; i++) {
                Integer numIndex = index.get(nums1[i]);
                res[i] = findNext(numIndex, nums2);
            }
            return res;
        }
        
        public int findNext(Integer numIndex, int[]nums2) {
            if (numIndex == null || (numIndex > nums2.length - 1)) {
                return -1;
            }
            int source = nums2[numIndex];
            for (int i = numIndex; i < nums2.length; i++) {
                if (nums2[i] > source) {
                    return nums2[i];
                } 
            }
            return -1;
        }
    }
    

Log in to reply
 

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