leetcode 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:
    static bool myfunction (int i, int j) {
        return (i==j);
    }
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> v;
        map<int,int> mp;
        for (int i = 0; i < nums1.size(); ++i) mp[nums1[i]]++;
        for (int i = 0; i < nums2.size(); ++i) {
            if (mp[nums2[i]] > 0) v.push_back(nums2[i]);
        }
        sort(v.begin(), v.end());
        std::vector<int>::iterator it;
        it = unique(v.begin(), v.end());
        v.resize( std::distance(v.begin(),it) );
        return v;
    }
};

 

posted on 2017-08-18 08:57  Beserious  阅读(152)  评论(0编辑  收藏  举报