题目地址:
https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
求两个数组 A A A和 B B B的交集,以数组形式返回。重复次数也要算在内。
代码如下:
class Solution {
public:
vector<int> intersect(vector<int>& a, vector<int>& b) {
unordered_map<int, int> mp;
for (int x : a) mp[x]++;
vector<int> res;
for (int x : b) {
if (!mp.count(x)) continue;
if (!--mp[x]) mp.erase(x);
res.push_back(x);
}
return res;
}
};
时间复杂度 O ( l A + l B ) O(l_A+l_B) O(lA+lB),空间 O ( l A ) O(l_A) O(lA)。