leetcode_c++:哈希:intersection of Two Arrays(349)

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

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

求两个数组的交集,元素不能重复。


算法

set


class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int>s1,s2;
        int n1=nums1.size(),n2=nums2.size();
        for(int i=0;ifor(int i=0;ivector<int>res;
        set<int>::iterator it1=s1.begin(),it2=s2.begin();
        while(it1!=s1.end()&&it2!=s2.end())
        {
            if(*it1==*it2)
            {
                res.push_back(*it1);
                it1++;
                it2++;
            }
            else if(*it1<*it2) it1++;
            else it2++;
        }
        return res;
    }
};

算法

map


class Solution {  
public:  
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {  
        map<int,int>m;  
        int n1=nums1.size(),n2=nums2.size();  
        for(int i=0;ivector<int>res;  
        for(int i=0;iif(m[nums2[i]]!=0)  
            {  
                res.push_back(nums2[i]);  
                m[nums2[i]]=0;  
            }  
        }  
        return res;  
    }  
};  

你可能感兴趣的:(leetcode(c++))