输入:两个整数数组 nums1, nums2
要求:返回它们的“交集数组”,即:
-
每个元素在结果中出现的次数
-
等于它在两个数组中出现次数的 最小值
-
不要求输出顺序
输出:一个数组
思路:用两个哈希表分别统计 nums1 与 nums2 中每个数字的出现次数,再对照取每个数字出现次数的 min(次数1, 次数2),把它加入结果即可。
复杂度:
时间复杂度:O(n + m)
空间复杂度:O(n + m)
#include <vector>
#include <unordered_map>
#include <algorithm> // for std::min
class Solution {
public:
std::vector<int> intersect(std::vector<int>& nums1, std::vector<int>& nums2) {
std::unordered_map<int, int> tmp1;
std::unordered_map<int, int> tmp2;
std::vector<int> ans;
for (int n : nums1) {
tmp1[n]++;
}
for (int n : nums2) {
tmp2[n]++;
}
for (auto const& pair : tmp1) {
int num = pair.first;
int count_in_1 = pair.second;
auto it = tmp2.find(num);
if (it != tmp2.end()) {
int count_in_2 = it->second;
int count = std::min(count_in_1, count_in_2);
for (int i = 0; i < count; ++i) {
ans.push_back(num);
}
}
}
return ans;
}
};

被折叠的 条评论
为什么被折叠?



