Leetcode题目: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 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) {
        sort(nums1.begin(), nums1.end());
        //vector<int>::iterator end_unique =  unique(nums1.begin(), nums1.end()); 
       // nums1.erase(end_unique, nums1.end());
        sort(nums2.begin(),nums2.end());
       // end_unique =  unique(nums2.begin(), nums2.end()); 
        //nums2.erase(end_unique, nums2.end());
        vector<int>::iterator nit1 = nums1.begin();
        vector<int>::iterator nit2 = nums2.begin();
        vector<int> res;
        while((nit1 != nums1.end())  && (nit2 != nums2.end()) )
        {
            if(*nit1 == *nit2)
            {
                res.push_back(*nit1);
                nit1++;
                nit2++;
            }
            else if(*nit1 < *nit2)
            {
                nit1++;
            }
            else
            {
                nit2++;
            }
            
        }
    return res;
    }
};

  

考虑到Followup中提到的,对nums2进行排序不太好,使用哈希来编码实现,代码如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> num_map;
        vector<int> res;
        for(auto nit = nums1.begin(); nit != nums1.end(); nit++)
        {
            num_map[*nit] += 1;
        }
        for(auto nit = nums2.begin(); nit != nums2.end(); nit++)
        {
            if(num_map[*nit] >= 1)
            {
                num_map[*nit] -= 1;
                res.push_back(*nit);
            }
            
        }
        return res;
    }
};

  

 

转载于:https://www.cnblogs.com/CodingGirl121/p/5542565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值