350. Intersection of Two Arrays

2016-09-16  本文已影响0人  a_void

iven two arrays, write a function to compute their intersection.
Example:Given nums1 =[1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:

Follow up:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        map<int, int> m = map<int, int>();
        vector<int> r = vector<int>();
        for(int i=0;i<nums1.size();i++)
            m[nums1[i]] += 1;
        for(int i=0;i<nums2.size();i++){
            if(m[nums2[i]] > 0){
                r.push_back(nums2[i]);
                m[nums2[i]]-=1;
            }
        }
        return r;
    }
};
上一篇下一篇

猜你喜欢

热点阅读