Leetcode - Intersection of Two Arrays II

My code:

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return null;
        }
        
        HashMap map = new HashMap();
        List retList = new ArrayList();
        
        for (int i = 0; i < nums1.length; i++) {
            if (!map.containsKey(nums1[i])) {
                map.put(nums1[i], 1);
            }
            else {
                map.put(nums1[i], map.get(nums1[i]) + 1);
            }
        }
        
        for (int i = 0; i < nums2.length; i++) {
            if (!map.containsKey(nums2[i])) {
                continue;
            }
            else {
                retList.add(nums2[i]);
                map.put(nums2[i], map.get(nums2[i]) - 1);
                if (map.get(nums2[i]) == 0) {
                    map.remove(nums2[i]);
                }
            }
        }
        
        int[] ret = new int[retList.size()];
        for (int i = 0; i < retList.size(); i++) {
            ret[i] = retList.get(i);
        }
        return ret;
    }
}

和 I 差不多,思路很直接。
下面讨论下他的三个 follow up

1 . What if the given array is already sorted? How would you optimize your algorithm?
2 . What if nums1's size is small compared to nums2's size? Which algorithm is better?
3 . What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

1 . 可以用类似于merge sort 的办法, 双指针。
2 . 对较长的 array 作 sort, 然后,遍历较短的array,拿出它的元素,去较长的array里面做 binary search,找到之后,标记已经用过。
plus: 这个方法好像不太好。上面的两个方法对这个问题都适用啊,复杂度是 O(m + n)

3 .
reference:
https://discuss.leetcode.com/topic/45992/solution-to-3rd-follow-up-question

如果,只有一个数组放不进去。那么,可以用hashtable的方法,然后每次read chunk of that big array

如果,两个都放不进去,那么就用 排序的方法。
对两个数组分别进行 external sort
然后再双指针 merge。

External Sort:
http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L17-ExternalSortEX2.htm

Anyway, Good luck, Richardo! -- 09/21/2016

你可能感兴趣的:(Leetcode - Intersection of Two Arrays II)