My solution, time complexity O(m*n):

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0;i<nums2.length;i++){
            map.put(nums2[i], i);
        }
        
        int[] res = new int[nums1.length];
        a:for(int i=0;i<nums1.length;i++){
            int index = map.get(nums1[i]);
            for(int j=index+1;j<nums2.length;j++){
                if(nums2[j]>nums1[i]){
                    res[i]=nums2[j];
                    continue a;
                }
            }
            res[i]=-1;
        }
        return res;
    }
}

Two pass skack solution, time complexity: O(n)

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        Stack<Integer> stk = new Stack<>();
        for(int i=0;i<nums2.length;i++){
            while(!stk.isEmpty() && nums2[i]>stk.peek()){
                map.put(stk.pop(), nums2[i]);
            }
            stk.push(nums2[i]);
        }
        
        int[] res = new int[nums1.length];
        for(int i=0;i<nums1.length;i++){
            if(map.containsKey(nums1[i])){
                res[i]=map.get(nums1[i]);
            }
            else
                res[i]=-1;
        }
        return res;
    }
}

 

posted on 2022-04-20 09:52  阳光明媚的菲越  阅读(22)  评论(0编辑  收藏  举报