https://leetcode.com/problems/intersection-of-two-arrays/description/
题目: 求集合的交集。
第一种解法,直接用set集合。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int>temp(nums1.begin(),nums1.end()),temp1;
vector<int>result;
int len1=nums1.size(),len2=nums2.size();
for(int x=0;x<len2;x++)
if(temp.count(nums2[x])&&!temp1.count(nums2[x]))
temp1.insert(nums2[x]),result.push_back(nums2[x]);
return result;
}
};
第二种,使用 set_intersection函数。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int>temp1(nums1.begin(),nums1.end()),temp2(nums2.begin(),nums2.end()),temp3;
set_intersection(temp1.begin(), temp1.end(), temp2.begin(), temp2.end(), inserter(temp3, temp3.begin()));
vector<int>result(temp3.begin(),temp3.end());
return result;
}
};