350. Intersection of Two Arrays II

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

Example 1:

Input: 
nums1 = [1,2,2,1], nums2 = [2,2]
Output: 
[2,2]

Example 2:

Input: 
nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: 
[4,9]

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?

Example 1:

Input: 
nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: 
nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Thoughts:

  1. Hashtable implementaion:

    1. Time: O(m + n) Space: O(m + n)

    2. Time: O(m + n) Space: O(m)

  2. Sort + two pointers Solution:

    1. Time: O(max(m,n)log(max(m,n)) Space: O(m + n)

Code: Hashtable implementaion Time: O(m + n) Space: O(m + n)

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> map;
        vector<int> res;
        for (int i = 0; i < nums1.size(); i++) map[nums1[i]]++;
        for (int i = 0; i < nums2.size(); i++) {
            if(--map[nums2[i]] >= 0) res.push_back(nums2[i]);
        }

        return res;
    }
};

Code: Time: O(m + n) Space: O(m)

  1. change if(--map[nums2[i]] >= 0) res.pushback(nums2[i]) to if(map.find(nums2[i])!=map.end() && --map[nums2[i]]>= 0 res.push_back(nums2[i])

Code: Sort + Two Pointers:
Time: O(max(m + n, mlogm, nlogn)) Space: O(m + n)

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int m = nums1.size(), n = nums2.size();
        vector<int> res;
        int i1 = 0, i2 = 0;
        while(i1 < m && i2 < n){
            if(nums1[i1] == nums2[i2]){
                res.push_back(nums1[i1]);
                i1++;
                i2++;
            }
            else if (nums1[i1] > nums2[i2]){
                i2++;
            }
            else {
                i1++;
            }
        }

        return res;
    }
};

Follow up:

  1. two pointer: Time: max(m + n, mlogm, nlogn), Space O(1)
  2. Suppose lengths of two arrays areNandM, the time complexity of my solution isO(N+M)and the space complexity ifO(N)considering the hash. So it's better to use the smaller array to construct the counter hash. Well, as we are calculating the intersection of two arrays, the order of array doesn't matter. We are totally free to swap to arrays.

  3. Divide and conquer. Repeat the process frequently: Slicenums2to fit into memory, process (calculate intersections), and write partial results to memory.

results matching ""

    No results matching ""