Intersection of Two Arrays II

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

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

 

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to num2's size? Which algorithm is better?

  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
#include<iostream>
#include<set>
#include<vector>
#include<map>
#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,1 };
	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)
{
	vector<int>temp;
	//map<int, int> m;
	//for (auto data : a)
	//	m[data]++;
	//// map常用于统计数组中一个数的个数
	//for (auto data : b)
	//{
	//	if (m[data] > 0)
	//	{
	//		temp.push_back(data);
	//		m[data]--;
	//	}
	//}
	sort(a.begin(), a.end());
	sort(b.begin(), b.end());
	int i = 0, j = 0;
	//不排序的话 不能判断重复数字
	while (i < a.size() && j < b.size())
	{
		if (a[i] == b[j])
		{
			temp.push_back(a[i]);
			i++;
			j++;
		}
		else
		{
			if (a[i]>b[j])
			{
				j++;
			}
			else
			{
				i++;
			}
		}
	}
	return temp;
}


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