2016年10月11日星期二

350. 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].
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?
  • 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), 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.
    But I am not sure this solution is good enough for an interview setting. Maybe the interviewer is expecting some solution using Map-Reduce paradigm.

    Solution 1: hashtable (using unordered_map).
    • time complexity: max(O(m), O(n))
    • space complexity: choose one O(m) or O(n) <--- So choose the
      smaller one if you can
    Solution 2: sort + binary search
    • time complexity: max(O(mlgm), O(nlgn), O(mlgn)) or max(O(mlgm),
      O(nlgn), O(nlgm))
    • O(mlgm) <-- sort first array
    • O(nlgn) <--- sort second array
    • O(mlgn) <--- for each element in nums1, do binary search in nums2
    • O(nlgm) <--- for each element in nums2, do binary search in nums1
    • space complexity: depends on the space complexity used in your
      sorting algorithm, bounded by max(O(m), O(n)
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> ret;
        if(nums1.empty() || nums2.empty()) return ret;
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int j=0;
        for(int i=0; i<nums1.size(); ) {
            int index = lower_bound(nums2, nums1[i]);
            int count2 = 0;
            while(index<nums2.size() && nums2[index]==nums1[i]) {
                count2++; 
                index++;
            }
            int count1 = 0;
            while(nums1[j]==nums1[i]) {
                count1++;
                j++;
            }
            ret.insert(ret.end(),min(count1,count2),nums1[i]);
            i=j;
        } 
        return ret;
    }

    没有评论:

    发表评论