Leetcode-349 Intersection of Two Arrays

Posted 北冥有鱼,南冥有猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode-349 Intersection of Two Arrays相关的知识,希望对你有一定的参考价值。

#349.  Intersection of Two Arrays    

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

    • Each element in the result must be unique.
    • The result can be in any order.

题解:我想到的是用set,有点懒,其实是不知道咋做好,直接上代码。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> v(0);
        vector<int> ret;
        if(nums1.size()==0||nums2.size()==0)
            return v;
        set<int> save;
        set<int> result;
        for(int i=0;i<nums1.size();i++)
        {
            save.insert(nums1[i]);
        }
        for(int i=0;i<nums2.size();i++)
        {
            if(save.find(nums2[i])!=save.end())
            {
                result.insert(nums2[i]);
            }
        }
        set<int>::iterator it;
        for(it=result.begin();it!=result.end();it++)
        {
            ret.push_back(*it);
        }
        return ret;
    }
};

 

      


以上是关于Leetcode-349 Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]349.Intersection of Two Arrays

Leetcode-349 Intersection of Two Arrays

LeetCode(349)Intersection of Two Arrays

leetcode349. Intersection of Two Arrays

LeetCode 349 Intersection of Two Arrays

[leetcode-349-Intersection of Two Arrays]