0%

leetcode每日一题-两个数组的交集II

两个数组的交集II

image1

方法一:哈希表

由于同一个数字在两个数组中都可能出现多次,因此需要用哈希表存储每个数字出现的次数。对于一个数字,其在交集中出现的次数等于该数字在两个数组中出现次数的最小值。

首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数,然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。

为了降低空间复杂度,首先遍历较短的数组并在哈希表中记录每个数字以及对应出现的次数,然后遍历较长的数组得到交集。

1
class Solution {
2
    public int[] intersect(int[] nums1, int[] nums2) {
3
        if (nums1.length > nums2.length) {
4
            return intersect(nums2, nums1);
5
        }
6
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
7
        for (int num : nums1) {
8
            int count = map.getOrDefault(num, 0) + 1;
9
            map.put(num, count);
10
        }
11
        int[] intersection = new int[nums1.length];
12
        int index = 0;
13
        for (int num : nums2) {
14
            int count = map.getOrDefault(num, 0);
15
            if (count > 0) {
16
                intersection[index++] = num;
17
                count--;
18
                if (count > 0) {
19
                    map.put(num, count);
20
                } else {
21
                    map.remove(num);
22
                }
23
            }
24
        }
25
        return Arrays.copyOfRange(intersection, 0, index);
26
    }
27
}

复杂度分析

  • 时间复杂度:$O(m+n)$,$m$和$n$分别是两个数组的长度。
  • 空间复杂度:$O(min(m,n))$。

##方法二:排序

如果两个数组是有序的,则可以便捷地计算两个数组的交集。

首先对两个数组进行排序,然后使用两个指针遍历两个数组。

初始时,两个指针分别指向两个数组的头部。每次比较两个指针指向的两个数组中的数字,如果两个数字不相等,则将指向较小数字的指针右移一位,如果两个数字相等,将该数字添加到答案,并将两个指针都右移一位。当至少有一个指针超出数组范围时,遍历结束

1
class Solution {
2
    public int[] intersect(int[] nums1, int[] nums2) {
3
        Arrays.sort(nums1);
4
        Arrays.sort(nums2);
5
        int length1 = nums1.length, length2 = nums2.length;
6
        int[] intersection = new int[Math.min(length1, length2)];
7
        int index1 = 0, index2 = 0, index = 0;
8
        while (index1 < length1 && index2 < length2) {
9
            if (nums1[index1] < nums2[index2]) {
10
                index1++;
11
            } else if (nums1[index1] > nums2[index2]) {
12
                index2++;
13
            } else {
14
                intersection[index] = nums1[index1];
15
                index1++;
16
                index2++;
17
                index++;
18
            }
19
        }
20
        return Arrays.copyOfRange(intersection, 0, index);
21
    }
22
}

复杂度分析

  • 时间复杂度:$O(mlogm+nlogn)$。
  • 空间复杂度:$O(min(m,n))$。

进阶:

  1. 排好序的数组参考方法二。
  2. $nums1$小很多的话推荐第一种方法,可以节省空间。
  3. 使用第一种方法,在第一种方法中$nums2$只涉及到查询,因此可以分批将$nums2$读入内存并进行查询处理。