349. Intersection of Two Arrays

找兩個(gè)字符串的intersection。Intersection在這里是數(shù)學(xué)上「交集」的意思。

原始代碼:
用了兩個(gè)set,另外還用了很蠢的方法set轉(zhuǎn)換成int數(shù)組。。

    //Approach1: 兩個(gè)hashset,第一個(gè)存儲(chǔ)nums1中的unique numbers,然后輪詢第二個(gè)數(shù)組
    // 判斷第一個(gè)是否contains,然后加入一個(gè)新的HashSet,Time: O(n2)

    //Approach2: 用一個(gè)超大的數(shù)組模擬map。。

        //以下是Approach1
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> res = new HashSet<>();
        for (Integer num : nums1) {
            set1.add(num);
        }
        for (int num : nums2) {
            if (set1.contains(num)) {
                res.add(num);
            }
        }

        Object[] arr = res.toArray();
        int[] result = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            result[i] = (int) arr[i];
        }
        return result;
    }

Review:

  1. HashSet可以直接遍歷:
        for (Integer num : intersect) {
            result[i++] = num;
        }
  1. 還可以用排序然后雙指針。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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