输入:两个数组 nums1 和 nums2。
要求:返回它们的交集,输出结果中每个元素 唯一,顺序无关。
思路:
- 使用
map<int, array<int,2>>或者unordered_map<int, array<int,2>>来记录两个数组是否出现。- 当元素在
nums1出现时,标记flag[0] = 1。 - 当元素在
nums2出现时,标记flag[1] = 1。
- 当元素在
- 最终遍历 map,把同时出现在两个数组的元素加入结果。
复杂度:
- 时间复杂度:O(m + n),m 和 n 分别是两个数组长度。
- 空间复杂度:O(m + n),主要用于 map 存储。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, array<int,2>> mp;
vector<int> ans;
for (int x : nums1) {
mp[x][0] = 1; // 在 nums1 出现
}
for (int x : nums2) {
mp[x][1] = 1; // 在 nums2 出现
}
for (auto &p : mp) {
if (p.second[0] == 1 && p.second[1] == 1) {
ans.push_back(p.first);
}
}
return ans;
}
};

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



