RE . 349. Intersection of Two Arrays

本文介绍了一种计算两个整数数组交集的算法实现。通过排序和哈希表两种方法来找出两个数组中的共有元素,并确保结果中每个元素都是唯一的。提供了详细的C++代码示例。

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

                   简单的 用排序

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> ans;
        //if((nums1.empty()) || (nums2.empty()))
       // return nums;
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int i = 0, j = 0;
        while((i < nums1.size()) && (j < nums2.size()))
        {
            if(nums1[i] == nums2[j])
            {
                if(ans.empty()||nums1[i] != ans[ans.size()-1])   // 如果这里把ans.empty 放到||后面就会报错。  要先检测是否是空!
                    ans.push_back(nums1[i]);
                ++i;
                ++j;
            }
            else nums1[i]<nums2[j]? i++:j++;
            
        }
        return ans;
        
    }
};

                    看不懂的答案。。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> m(nums1.begin(), nums1.end());  //这是啥
        vector<int> res;
        for (auto a : nums2)
            if (m.count(a)) {
                res.push_back(a);
                m.erase(a);
            }
        return res;
    }
};




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值