Intersection of Two Arrays 2

本文介绍了一种寻找两个数组中重复元素的高效算法。通过使用哈希表存储第一个数组的元素及其出现次数,然后遍历第二个数组,如果元素存在于哈希表中且计数大于零,则将其添加到结果列表中,并减少哈希表中该元素的计数。这种方法避免了双重循环的复杂度,提高了查找效率。

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

寻找两个数组中共同重复的数字,并将他们装到一个数组中

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // 注释部分为最长的具有相同顺序的最长数组
        // ArrayList<Integer> list = new ArrayList<>();
        // for(int i=0;i<nums1.length;i++){
        //     for(int j=0;j<nums2.length;j++){
        //         if(nums1[i] == nums2[j]){
        //             int tempi = i;
        //             int tempj = j;
        //             List<Integer> tempList = new ArrayList<>();
        //             while(tempi < nums1.length && tempj < nums2.length && nums1[tempi] == nums2[tempj]){
        //                 tempList.add(nums1[tempi]);
        //                 tempi++;
        //                 tempj++;
        //             }
        //             if(tempList.size() > list.size()){
        //                 list = new ArrayList<>(tempList);
        //             }
        //         }
        //     }
        // }
        // int[] res = new int[list.size()];
        // for(int i=0;i<list.size();i++){
        //     res[i] = list.get(i);
        // }
        // return res;
        
        Map<Integer,Integer> map = new HashMap<>();
        List<Integer> list= new ArrayList<>();
        for(int i=0;i<nums1.length;i++){
            map.put(nums1[i],map.getOrDefault(nums1[i],0) + 1);
        }
        
        for(int i=0;i<nums2.length;i++){
            if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0){
                list.add(nums2[i]);
                map.put(nums2[i],map.get(nums2[i]) - 1);
            }
        }
        int[] res = new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
        
        
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值