Easy | LeetCode 350. 两个数组的交集 II | 哈希 | 排序+双指针

350. 两个数组的交集 II

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]

方法一: 哈希

将一个数组存储进HashMap中, 然后扫描第二个数组, 看Hashmap中是否存在。

public int[] intersect(int[] nums1, int[] nums2) {
    if (nums1.length > nums2.length) {
        return intersect(nums2, nums1);
    }
    // 将第一个数组的元素用HashMap统计
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int num : nums1) {
        int count = map.getOrDefault(num, 0) + 1;
        map.put(num, count);
    }
    int[] intersection = new int[nums1.length];
    int index = 0;
    for (int num : nums2) {
        // 统计第二个数组的每个元素在hashMap中出现的次数
        int count = map.getOrDefault(num, 0);
        if (count > 0) {
            // 如果出现, 则将当前元素添加进结果数组
            intersection[index++] = num;
            count--;
            if (count > 0) {
                map.put(num, count);
            } else {
                map.remove(num);
            }
        }
    }
    // 数组截取
    return Arrays.copyOfRange(intersection, 0, index);
}

方法二: 排序 + 双指针

public int[] intersect(int[] nums1, int[] nums2) {
    // 首先将两个数组排序
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int length1 = nums1.length, length2 = nums2.length;
    int[] intersection = new int[Math.min(length1, length2)];
    // 然后使用双指针比较元素
    int index1 = 0, index2 = 0, index = 0;
    while (index1 < length1 && index2 < length2) {
        if (nums1[index1] < nums2[index2]) {
            index1++;
        } else if (nums1[index1] > nums2[index2]) {
            index2++;
        } else {
            // 将两个指针指向的元素相同时, 将元素添加进结果集
            intersection[index] = nums1[index1];
            // 然后两指针同步向前走
            index1++;
            index2++;
            index++;
        }
    }
    return Arrays.copyOfRange(intersection, 0, index);
}
原文地址:https://www.cnblogs.com/chenrj97/p/14457491.html