Intersection of Two Arrays

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

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

Note:

  • Each element in the result must be unique.

  • The result can be in any order.
#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;

vector<int> intersection(vector<int>a, vector<int>b);
int  main()
{
	vector<int>a = { 1, 2, 2, 1 };
	vector<int>b = { 2, 2 };
	vector<int>temp;
	temp = intersection(a, b);
	for (int d : temp)
		cout << d << endl;

	system("pause");
	return 0;
}
vector<int> intersection(vector<int>a, vector<int>b)
{
	set<int>s(a.begin(), a.end());
	vector<int>result;
	//因为得保持没重复的,最好是用set;
	for (auto data : b)
	{
		if (s.count(data)) result.push_back(data);
	}
	set<int>m(result.begin(),result.end());
	vector<int>temp(m.begin(), m.end());
	return temp;
}


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