leetCode 350. Intersection of Two Arrays II 哈希

发布时间:2020-07-02 09:47:44 作者:313119992
来源:网络 阅读:819

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:


Follow up:

题目大意:

找出两个数组中相同元素,相同元素的个数可以大于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

推荐阅读:
  1. LeetCode167. Two Sum II - Input array is sorted C语言
  2. leetcode   Two Sum

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

table hash ers

上一篇:影响linux运行速度的因素是什么

下一篇:Godaddy ssl证书有哪些特点

相关阅读

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

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