代码随想录-哈希表-3.两个数组的交集

文章介绍了在LeetCode平台上如何使用Java编程语言解决数组交集问题,提供了两种方法:一种是利用HashSet存储并遍历,另一种是借助HashMap记录元素及其出现次数。
摘要由CSDN通过智能技术生成

. - 力扣(LeetCode)

import java.util.HashSet;
import java.util.Set;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        //遍历数组1
        for (int i : nums1) {
            set1.add(i);
        }
        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
      
        //方法1:将结果集合转为数组

        return resSet.stream().mapToInt(x -> x).toArray();
//这行代码先创建stream,之后转为int型,最后转为数组

        
        //方法2:另外申请一个数组存放setRes中的元素,最后返回数组
        int[] arr = new int[resSet.size()];
        int j = 0;
        for(int i : resSet){
            arr[j++] = i;
        }
        
        return arr;
    }
}

参考:List的toArray()方法_list.toarray-CSDN博客 

又LIst转为int[] 的几种方法。

. - 力扣(LeetCode)

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        //建立一个哈希表,先保存短的数组出现的数字和出现个数
        //建立一个数组,保存相交的元素
        if(nums1.length>nums2.length){
            return intersect(nums2,nums1);//如果nums1的长度比nums2的长度大,那就将1和2交换,然后执行intersect方法
            //为了保证遍历的是比较短的数组,为了降低空间复杂度
        }
        HashMap<Integer,Integer> map1 = new HashMap();
        for(int i:nums1){
            int num = map1.getOrDefault(i,0)+1;//如果map1中不存在i,就返回0+1,存在就返回对应的values+1
            map1.put(i,num);       
        }
        int[] result = new int[nums2.length];//创建一个和nums2的长度相等的数组,因为相交部分最长和较长的数组相等
        int index=0;//计数result的元素个数
        for(int i=0;i<nums2.length;i++){
            int count = map1.getOrDefault(nums2[i],0);//count用来计数,大于0就证明有相交部分,相交的个数为count值,为0就
            //证明这个元素不重合
            if(count>0){
                result[index]=nums2[i];
                count--;
                index++;
                if(count>0){//如果剪完1count还是大于0,更新map1
                    map1.put(nums2[i],count);
                }else{//如果剪完count=0,删掉这元素
                    map1.remove(nums2[i]);
                }
            }
        }
        return Arrays.copyOfRange(result,0,index);//Arrays.copyOfRange主要用于对一个已有的数组进行截取复制,复制出一个左闭右开区间的数组。
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值