Intersection of Two Arrays II

求两个集合的交集,用map来记录出现次数,unordered_map效率更高。

vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int> map1;
        unordered_map<int,int>::iterator it;
        int len1 = nums1.size();
        for(int i=0;i<len1;++i)
        {
            int key = nums1[i];
            it= map1.find(key);
            if(it == map1.end())
            {
                map1[key] = 1;
            }
            else
            {
                map1[key]++;
            }
        }

        int len2 = nums2.size();
        vector<int> ret;
        for(int i=0;i<len2;++i)
        {
            int key = nums2[i];
            it = map1.find(key);
            if(it != map1.end())
            {
                if(map1[key] > 0)
                {
                    ret.push_back(key);
                    map1[key]--;
                }
            }
        }

        return ret;
    }

你可能感兴趣的:(Intersection of Two Arrays II)