LeetCode350-两个数组的交集II

题目链接

英文链接:https://leetcode.com/problems/intersection-of-two-arrays-ii/

中文链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/

题目详述

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

示例 1:

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

示例 2:

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

说明:

  • 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
  • 我们可以不考虑输出结果的顺序。

进阶:

  • 如果给定的数组已经排好序呢?你将如何优化你的算法?
  • 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
  • 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

题目详解

LeetCode349-两个数组的交集 和本题都是取两个数组的交集,解题思路是一致的,区别在于前者结果中没有重复元素,后者结果中可以有重复元素。

方法一:运用 HashMap。

  • 遍历 nums1, 统计每个元素出现的次数。
  • 遍历 nums2,判断当前元素是否在 map 中出现过且次数大于 0。若满足要求则添加当前元素到结果集中,并将统计次数减一。
  • 时间复杂度为 O(n + m),n、m 为数组 nums1、nums2 的长度。
  • 空间复杂度为 O(n)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class LeetCode_00350 {

public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums1) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer> list = new ArrayList<>();
for (int num : nums2) {
int val = map.getOrDefault(num, 0);
if (val > 0) {
list.add(num);
map.put(num, val - 1);
}
}
int i = 0;
int[] res = new int[list.size()];
for (int num : list) {
res[i++] = num;
}
return res;
}
}

方法二:运用双指针。

  • 先对两个数组进行排序,再运用双指针进行扫描。
  • 时间复杂度为 O(nlongn) + O(mlogm) + O(n + m)。
  • 空间复杂度为 O(1)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class LeetCode_00350 {

public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int n1 = nums1.length;
int n2 = nums2.length;
int i = 0;
int j = 0;
while (i < n1 && j < n2) {
if (nums1[i] < nums2[j]) {
++i;
} else if (nums1[i] > nums2[j]) {
++j;
} else {
list.add(nums1[i]);
++i;
++j;
}
}
i = 0;
int[] res = new int[list.size()];
for (int num : list) {
res[i++] = num;
}
return res;
}
}

进阶:

  1. 如果给定的数组已经排好序呢?你将如何优化你的算法?
    • 运用双指针,时间复杂度为 O(n + m)。
    • 运用二分查找,时间复杂度为 O(nlogm)。
  2. 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
    • 将 nums1 存入哈希表,遍历 nums2,时间复杂度为 O(n + m)。
    • 遍历 nums1,对 nums2 进行二分查找,时间复杂度为 O(nlogm)。
  3. 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
    • 如果 nums1 可以存入内存,可以将 nums1 存入哈希表,分块读入 nums2。
    • 如果 nums1 也不能存入内存,可以对 nums1 和 nums2 进行外部排序,分块读入内存,运用双指针进行查找。