1

Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
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?

排序+双指针

复杂度

O(Min(N,M)) 时间 O(Min(N,M)) 空间

思路

先排序,用两个指针从头扫:
小的那个肯定不行,指针往后
相等的全都放到result里

注意

没有

代码

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> result = new ArrayList<Integer>();
        int i = 0, j = 0;
        while (i < nums1.length && j < nums2.length) {
            int n1 = nums1[i];
            int n2 = nums2[j];
            if (n1 == n2) {
                result.add(n1);
                i++;
                j++;
            }
            else if (n1 < n2)
                i++;
            else
                j++;
        }
        int[] ret = new int[result.size()];
        int k = 0;
        for (int num : result)
           ret[k++] = num;
        return ret;
    }
}

Follow Up

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?

  • If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.

  • If both nums1 and nums2 are so huge that neither fit into the memory, sort them individually (external sort), then read (let's say) 2G of each into memory and then using the 2 pointer technique, then read 2G more from the array that has been exhausted. Repeat this until no more data to read from disk.


liuqi627
364 声望100 粉丝