349. Intersection of Two Arrays

找两个字符串的intersection。Intersection在这里是数学上「交集」的意思。

原始代码:
用了两个set,另外还用了很蠢的方法set转换成int数组。。

    //Approach1: 两个hashset,第一个存储nums1中的unique numbers,然后轮询第二个数组
    // 判断第一个是否contains,然后加入一个新的HashSet,Time: O(n2)

    //Approach2: 用一个超大的数组模拟map。。

        //以下是Approach1
    public int[] intersection(int[] nums1, int[] nums2) {
        Set set1 = new HashSet<>();
        Set 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. 还可以用排序然后双指针。

你可能感兴趣的:(349. Intersection of Two Arrays)