350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        if(nums2.size()==0 || nums1.size()==0)
            return res;
        
        unordered_map<int,int> hashTable1;
        
        for(auto num:nums1)
            ++hashTable1[num];
        
        for(auto num:nums2)
        {
            if(--hashTable1[num] >=0 )
                res.push_back(num);
        }
        
        return res;
        
    }
};

 

posted on 2017-03-05 06:13  123_123  阅读(68)  评论(0编辑  收藏  举报