首页 > 其他 > 详细

leetcode 349. Intersection of Two Arrays

时间:2017-08-18 09:13:39      阅读:234      评论:0      收藏: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.

判断两个数组的交集,去掉重复的。我们可以用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;
    }
};

 

leetcode 349. Intersection of Two Arrays

原文:http://www.cnblogs.com/pk28/p/7387684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!