查找三个数组的公共元素
大约 1 分钟
#include <iostream>
#include <vector>
#include <unordered_set>
using std::cout;
using std::endl;
using std::cin;
using std::vector;
using std::unordered_set;
//因为set比数组占用的空间大,并且set把数值映射到key都要做hash计算,速度也比数组慢
//如果数组数值范围可控可以使用数组做hash
const int M = 20; //数值的范围
vector<int> getIntersection3(const vector<int>& nums1, const vector<int>& nums2) {
unordered_set<int> result_set; //给结果去重
int hashTable[M] = {0};
for(int num : nums1) {
hashTable[num] = 1;
}
for(int num : nums2) {
if(hashTable[num] == 1) {
result_set.insert(num);
}
}
return vector(result_set.begin(), result_set.end());
}
void print(const vector<int>& vec) {
for(int i : vec) {
cout << i << ' ';
}
cout << endl;
}
int main() {
vector<int> v1 = { 1,2,2,3,4,5,5,5,8,9,11,13 };
vector<int> v2 = { 2,2,2,3,5,6,7,7,8,9,10,12,12,13,13,14 };
vector<int> v3 = { 1,1,1,2,2,4,5,6,7,7,8,9,10,14,14,17,18,20 };
//print(v1);
//print(v2);
//vector<int> ret = getIntersection(v1, v2);
//print(ret);
//vector<int> ret2 = getIntersection2(v1, v2);
//print(ret2);
//vector<int> ret3 = getIntersection3(v1, v2);
//print(ret3);
cout << "----------------三个有序数组的各个元素为" << endl;
print(v1);
print(v2);
print(v3);
vector<int> temp = getIntersection2(v1, v2);
vector<int> ret4 = getIntersection2(temp, v3);
print(ret4);
return 0;
}