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

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章