两个数组的交集-哈希表349-C++

算法思想:

一、没看答案

  • 用一个哈希表uomap存储其中一个数组的值,然后遍历另一个数组并在uomap中查找;
  • 如找到了并且res中没有该值,则push_back到res中,否则继续循环。

C++

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> uomap;
        vector<int> res;

        for(auto v : nums1){
            uomap[v];
        }
        for(auto v : nums2){
            if(uomap.find(v) != uomap.end() && find(res.begin(), res.end(), v) == res.end()){
                res.push_back(v);
            }
        }

        return res;
    }
};

复杂度分析:

  • 时间复杂度:O(m+n)。
  • 空间复杂度:O(m)。

二、集合去重

  • 可以利用unordered_set的集合去重性质解题。

C++

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> set_res;
        unordered_set<int> num_set(nums1.begin(), nums1.end());

        for(auto s : nums2){
            if(num_set.find(s) != num_set.end()){
                set_res.insert(s);
            }
        }

        return vector<int>(set_res.begin(), set_res.end());
    }
};

复杂度分析:

  • 时间复杂度:O(m+n)。
  • 空间复杂度:O(m)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值