LeetCode—两个数组的交集Ⅱ(排序对比+排序对比plus)

两个数组的交集Ⅱ(简单)

2020年6月20日

题目来源:力扣

在这里插入图片描述

解题
该题是昨天两个数组的交集的增强版,要求不能去重了。这种题,还是不想用哈希表来做。

  • 排序对比

用昨天的方法,只不过不去重了,排序之后进行对比

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if(nums1==null ||nums1.length==0 ||nums2==null ||nums2.length==0) return new int[0];
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int len1=nums1.length;
        int len2=nums2.length;
        int[] nums3=len1<len2 ? new int[len1+1]:new int[len2+1];
        int index=0,jb=0;
        for(int i=0;i<len1;i++){
            for(int j=jb;j<len2;j++){
                if(nums1[i]==nums2[j]){
                    nums3[index++]=nums1[i];
                    jb=j+1;
                    break;
                }
                else if(nums1[i]<nums2[j]){
                    jb=j;
                    break;
                }
            }
        } 
        return Arrays.copyOf(nums3,index);
    }
}

在这里插入图片描述

  • 排序对比plus

比起上个方法双重循环,单重循环效率会更好些
同时对两个数组进行查找,用nums1数组来存储最后的结果

class Solution {
        public int[] intersect(int[] nums1, int[] 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 (nums1[i] > nums2[j]) {
                ++j;
            } else {
                nums1[k++] = nums1[i++];
                ++j;
            }
        }
        return Arrays.copyOfRange(nums1, 0, k);
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值