6.LeetCode(初级算法)数组篇--两个数组的交集II c++

方法一、先排序再依次查找

class Solution {
public:
    vector intersect(vector& nums1, vector& nums2) {
        int size1,size2;
        vector out;
        size1 = nums1.size();
        size2 = nums2.size();
        if((size1 == 0) || (size2 == 0)) return out;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        int j=0;
        for(int i=0;i

方法二、采用unordered_multiset

class Solution{
public:
    vector intersect(vector& nums1, vector& nums2) {
    	unordered_multiset data;
    	vector out;
    	for(int& i : nums1) data.insert(i);
    	for(int& i : nums2)
    	{
    		if(data.count(i))
    		{
    			out.push_back(i);
    			data.erase(data.find(i));
    		}
    	}
    	return out;
    }
};

你可能感兴趣的:(LeetCode)