Easy to understand O(MN) Java solution


  • 1
    M
    public class Solution {
    public int[] nextGreaterElement(int[] findNums, int[] nums) {
        if(findNums == null ||  nums == null || 
           findNums.length == 0 || nums.length == 0 || 
           findNums.length > nums.length) return new int[0];
        
        int m = findNums.length;
        int n = nums.length;
        int[] result = new int[m];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        for(int j = 0; j < n; ++j){
            map.put(nums[j], j);
        }
        for(int i = 0; i < m; ++i){
            int j = map.get(findNums[i]);
            for(; j < n; ++j){
                if(nums[j] > findNums[i]) break;
            }
            result[i] = j < n ? nums[j] : -1;
        }
        return result;
    }
    }

  • 0
    G

    Good idea,we are almost same ,just as i use ArrayList() to get the index.but you are more careful as you judge the input at the begining.


Log in to reply
 

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