[Leetcode] 349. Intersection of

2016-05-28  本文已影响0人  gammaliu

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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读