美文网首页
[Leetcode] 349. Intersection of

[Leetcode] 349. Intersection of

作者: gammaliu | 来源:发表于2016-05-28 20:05 被阅读0次

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.

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> shortSet;
        set<int> returnSet;
        vector<int> ret;
        
        if(nums1.size() > nums2.size()){
            vector<int> tmp = nums1;
            nums1 = nums2;
            nums2 = tmp;
        }
        
        for(auto i = nums1.begin(); i != nums1.end(); i++){
            shortSet.insert(*i);
        }
        for(auto i = nums2.begin(); i != nums2.end(); i++){
            if(shortSet.count(*i) > 0){
                returnSet.insert(*i);
            }
        }
        for(auto i = returnSet.begin(); i != returnSet.end(); i++){
            ret.push_back(*i);
        }
        return ret;
    }
};

相关文章

网友评论

      本文标题:[Leetcode] 349. Intersection of

      本文链接:https://www.haomeiwen.com/subject/apofdttx.html