350. 两个数组的交集 II
题目描述
哈希映射实现
#pragma once
#include <iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution
{
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
{
unordered_map<int, int> hashmap;
for (int key : nums1)
{
++hashmap[key];
}
vector<int> intersection;
for (int num : nums2)
{
if (hashmap.count(num))
{
intersection.push_back(num);
--hashmap[num];
if (hashmap[num] == 0)
{
hashmap.erase(num);
}
}
}
return intersection;
}
};
int main()
{
int arry1[] = { 4,9,5 };
int arry2[] = { 9,4,9,8,5 };
vector<int> nums1;
vector<int> nums2;
for (int num1 : arry1)
{
nums1.push_back(num1);
}
for (int num2 : arry2)
{
nums2.push_back(num2);
}
Solution S;
vector<int> intersection;
intersection = S.intersect(nums1, nums2);
for (auto it = intersection.begin(); it != intersection.end(); it++)
{
cout << *it << " ";
}
cout << endl;
system("pause");
return 0;
}
运行结果
提交结果