首页 > 代码库 > Leetcode-349 Intersection of Two Arrays

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