350. Intersection of Two Arrays II

本文介绍了一种求两个整数数组交集的算法实现。通过使用哈希表记录第一个数组中的元素及其出现次数,然后遍历第二个数组,查找并输出匹配的元素,同时更新哈希表中对应元素的计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求二个数组的交集:遍历数组nums1,将其中的元素放入hash表,hash表的键值为数组元素,属性值为出现的次数;

 

遍历数组nums2,同时查询hash表,输出满足要求的数组元素。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int> table;
        for(int i=0;i<nums1.size();i++)
        {
            if(table.find(nums1[i])==table.end())
                table[nums1[i]]=1;
            else
                table[nums1[i]]++;
        }  //add element into the table
        
        unordered_map<int,int> res=table;
        vector<int> ans;
        for(int i=0;i<nums2.size();i++)
        {
            if(table.find(nums2[i])!=table.end())
            {
                if(table[nums2[i]]>0)
                    ans.push_back(nums2[i]);
                
            table[nums2[i]]--;
            }
        }
        
        return ans;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值