C ++中两个数组的交集
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2){
unordered_map<int, int> mp1, mp2;
vector<int> res;
for (auto x : nums1)
mp1[x]++;
for (auto x : nums2)
mp2[x]++;
for (auto x : mp1) {
int cnt = 0;
cnt = min(x.second, mp2[x.first]);
if (cnt > 0)
res.push_back(x.first);
}
return res;
}
};
main(){
Solution ob;
vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};
print_vector(ob.intersection(v, v1));
}
输入值
{1,5,3,6,9},{2,8,9,6,7}
输出结果
[9, 6, ]
以上是 C ++中两个数组的交集 的全部内容, 来源链接: utcz.com/z/338460.html