Monday, January 15, 2018

[2018-Interview] Intersection of Two Arrays II

Original question: https://leetcode.com/problems/intersection-of-two-arrays-ii/

Answer: Use a map to store the <number, count> pair, count is how many times the number appear in 1 single array.



class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
            return new int[0];
        }
        Map<Integer, Integer> numsCountMap = new HashMap<Integer, Integer>();
        if (nums1.length >= nums2.length) {
            return helper(nums1, nums2, numsCountMap);
        } else {
            return helper(nums2, nums1, numsCountMap);
        }
    }

    private int[] helper(int[] numsLong, int[] numsShort, Map<Integer, Integer> numsCountMap) {
        int[] result = new int[numsShort.length];
        for (int num : numsLong) {
            int count = numsCountMap.getOrDefault(num, 0);
            count++;
            numsCountMap.put(num, count);
        }
        int index = 0;
        for (int num : numsShort) {
            if (numsCountMap.containsKey(num)) {
                int existingCount = numsCountMap.get(num);
                if (existingCount > 0) {
                    result[index] = num;
                    existingCount --;
                    numsCountMap.put(num, existingCount);
                    index ++;
                }
            }
        }
        int[] finalResult = new int[index];
        for(int i = 0 ; i < index; i++) {
            finalResult[i] = result[i];
        }
        return finalResult;
    }
}

No comments:

Post a Comment