Leetcode 350. Intersection of Two Arrays II(分别用HashMap和排序实现)

Leetcode 350. Intersection of Two Arrays II

题目链接: Intersection of Two Arrays II

难度:easy

题目大意:

输入两个数组,输出两个数组共有的元素,如果同一个元素多次重复,全部输出。

思路:

思路1:

用HashMap来统计数组nums1中的各个元素出现的次数,再遍历nums2,如果nums2中的元素在HashMap中存在,且出现次数大于零,则将这个元素存起来,并将HashMap中该元素的次数减一。最后将存起来的所有元素返回。

思路2:

先将nums1和nums2排序,分别遍历nums1和nums2,如果碰到两个数组中的元素相等,则将该元素存起来,最后返回存起来的元素。该方法比思路1更快。

代码

思路1(用HashMap实现):
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        TreeMap<Integer,Integer> map=new TreeMap<>();
        for(int n:nums1){//统计nums1中各个数字出现的次数
            map.put(n,map.getOrDefault(n,0)+1);
        }
        ArrayList<Integer> result=new ArrayList<Integer>();
        for(int i=0;i<nums2.length;i++){ 
            if(map.containsKey(nums2[i])&&map.get(nums2[i])>0){
                result.add(nums2[i]);
                map.put(nums2[i],map.get(nums2[i])-1);
            }//map.get(nums2[i])减为0时,代表两个数组共有的某个数字已全部加入到result中  
        }
        
        int []res=new int[result.size()];
        for(int i=0;i<result.size();i++){
            res[i]=result.get(i);
        }
        return res;
    }
}
思路2(排序实现):
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
         //高赞回答
        if(nums1.length==0){
            return nums1;
        }
        if(nums2.length==0){
            return nums2;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i=0,j=0,k=0;
        while(i<nums1.length&&j<nums2.length){
            if(nums1[i]<nums2[j]){
                i++;
            }
            else if(nums2[j]<nums1[i]){
                j++;
            }
            else{
                nums1[k++]=nums1[i];
                i++;
                j++;
            }
        }
        return Arrays.copyOfRange(nums1,0,k);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值