让我们看下面的实现以更好地理解-
#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, ]