LC.349 | 两个数组的交集 | 数组 | 哈希表 | std::map

输入:两个数组 nums1nums2
要求:返回它们的交集,输出结果中每个元素 唯一,顺序无关。

思路:

  • 使用 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值