350. Intersection of Two Arrays II

来源:互联网 发布:深信服上网行为 js脚本 编辑:程序博客网 时间:2024/05/22 01:43

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 num2’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?

class Solution {public:    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        vector<int> intersection;        if(nums1.empty() || nums2.empty())        {            return intersection;        }        sort(nums1.begin(), nums1.end());        sort(nums2.begin(), nums2.end());        int m = nums1.size();        int n = nums2.size();        int i = 0,j = 0;        while(i < m && j < n)        {                 if(nums1[i] < nums2[j])                 {                     i++;                 }                 else if(nums1[i] > nums2[j])                 {                     j++;                 }                 else                 {                     intersection.push_back(nums1[i]);                     i++;                     j++;                 }         }        return intersection;    }};

Solution 1:
1. 如果不排序,O(mn)。
2. 如果m和n都在合理范围内,先排序,再一个一个对比,时间复杂度O(nlgn + mlgm + m+n)。
3. 如果m远小于n, 对n排序,m也排序(nlgn+mlgm+m+n),或者m不排序(nlgn + mn)。 这两种都差不多。也可以对m不排序,在n里做binary search,这样复杂度降低为nlgn+mlgn, 降很低。
4. 如果n很大,n只能存在disk上。只能把m load到内存,然后n一个一个的读进来,和m对比,这时m可以用hash存,这样复杂度就为O(n)了。

Solution2:
把数据1存在hash中,value记录出现的次数,每次match一次就减1。

class Solution {public:    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {        vector<int> intersection;        if(nums1.empty() || nums2.empty())        {            return intersection;        }        int m  = nums1.size();        int n = nums2.size();        unordered_map<int, int> data;        for(int i = 0; i < m; i++)        {           unordered_map<int,int>::iterator got = data.find (nums1[i]);           if(got == data.end())           {                data[nums1[i]] = 1;                          }           else           {               got->second +=1;           }        }        for(int j = 0; j < n; j++)        {            unordered_map<int,int>::iterator got = data.find (nums2[j]);            if(got==data.end())            {                continue;            }            else             {                if(got->second > 0)                {                    intersection.push_back(got->first);                    got->second -=1;                }                else                {                    continue;                }            }        }        return intersection;    }};
1 0