温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetCode 350. Intersection of Two Arrays II 哈希

发布时间:2020-07-02 09:47:44 来源:网络 阅读:818 作者:313119992 栏目:编程语言

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?

题目大意:

找出两个数组中相同元素,相同元素的个数可以大于1.

思路:

将数组2的元素放入multiset中。

遍历数组1,如果在multiset找到与数组1相等的元素,将该元素放入结果数组中,在multiset中删除第一个和这个元素相当的元素。

代码如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        multiset<int> set2;
        for(int i = 0; i < nums2.size(); i++)
            set2.insert(nums2[i]);
        for(int i = 0; i < nums1.size(); i++)
        {
            if(set2.find(nums1[i]) != set2.end())
            {
                result.push_back(nums1[i]);
                set2.erase(set2.find(nums1[i]));
            }
        }
        return result;
    }
};

2016-08-13 14:03:35

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI