Fork me on GitHub

[leetcode-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].

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?

思路:

用一个map去记录nums1里的数字出现次数,再去遍历nums2,统计是否出现过。

vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
     {
         vector<int>ret;
         map<int, int>mp;
         for (auto a : nums1)mp[a]++;
         for (auto a:nums2)
         {
             if (mp[a] > 0)
             {
                 mp[a]--;
                 ret.push_back(a);
             }
         }
         return ret;
     }

还有一种办法就是将nums1和nums2分别从小到大排序,然后用两个指针分别从头开始比较。

nums1[i]如果小于nums[j]就将i+1,如果大于就将j+1,如果相等同时+1,并记录。

vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int n1 = (int)nums1.size(), n2 = (int)nums2.size();
        int i1 = 0, i2 = 0;
        vector<int> res;
        while(i1 < n1 && i2 < n2){
            if(nums1[i1] == nums2[i2]) {
                res.push_back(nums1[i1]);
                i1++;
                i2++;
            }
            else if(nums1[i1] > nums2[i2]){
                i2++;
            }
            else{
                i1++;
            }
        }
        return res;
    }

 参考:

https://discuss.leetcode.com/topic/45893/c-hash-table-solution-and-sort-two-pointers-solution-with-time-and-space-complexity

posted @ 2017-07-08 21:52  hellowOOOrld  阅读(169)  评论(0编辑  收藏  举报