[LC] 349. Intersection of Two Arrays

這題真的很沒有營養,一個HashSet就能解決的問題。如果真的要變個花樣不用任何空間,排個序也可以,真的沒有什麼好思考的,直接給代碼就好了。

    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set = new HashSet<>();
        for (int i : nums1) set.add(i);
        HashSet<Integer> resSet = new HashSet<>();
        for (int i : nums2) {
            if (set.contains(i)) {
                resSet.add(i);
            }
        }
        
        int[] res = new int[resSet.size()];
        int cnt = 0;
        for (Integer i : resSet) {
            res[cnt] = i;
            cnt++;
        }
        
        return res;
    }

 

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