【數(shù)組】349. 兩個數(shù)組的交集 Easy

題目

給定兩個數(shù)組,編寫一個函數(shù)來計算它們的交集。

示例 1:

輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2]
示例 2:

輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出: [9,4]
說明:

輸出結(jié)果中的每個元素一定是唯一的。
我們可以不考慮輸出結(jié)果的順序。

思路

  1. 使用兩個Set O(n)
    public int[] intersection(int[] nums1, int[] nums2) {
        
        HashSet<Integer> record = new HashSet<>();
        HashSet<Integer> intersect = new HashSet<>();
        
        for(int a :nums1)
            record.add(a);
        
        for(int b: nums2)
            if(record.contains(b))
                intersect.add(b);
        
        int[] res = new int[intersect.size()];
        int i = 0;
        
        for(int r : intersect)
            res[i++]=r;
        
        return res;
    }
  1. 對數(shù)組排序,使用兩個指針 O(nlogn)
public int[] intersection2(int[] nums1, int[] nums2) {
       Set<Integer> set = new HashSet<>();       
       Arrays.sort(nums1);
       Arrays.sort(nums2);
       int i = 0;
       int j = 0;
       while (i < nums1.length && j < nums2.length) {
           if (nums1[i] < nums2[j]) {
               i++;
           } else if (nums1[i] > nums2[j]) {
               j++;
           } else {
               set.add(nums1[i]);
               i++;
               j++;
           }
       }
       int[] result = new int[set.size()];
       int k = 0;
       for (Integer num : set) {
           result[k++] = num;
       }
       return result;
   }
  1. 使用Set+List,O(n)
public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set = new HashSet<>();
        ArrayList<Integer> intersection = new ArrayList<>();
        
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        
        for (int i = 0; i < nums2.length; i++) {
            if (set.remove(nums2[i])) {
                intersection.add(nums2[i]);
            }
        }
        
        int[] result = new int[intersection.size()];
        for (int i = 0; i < intersection.size(); i++) {
            result[i] = intersection.get(i);
        }
        
        return result;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容