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);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/106867844