1.题目

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

示例:

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

说明:

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

进阶:

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

2.思路

哈希表:

来自官方解答:
350. 两个数组的交集 II - 图1
由于同一个数字在两个数组中都可能出现多次,因此需要用哈希表存储每个数字出现的次数。对于一个数字,其在交集中出现的次数等于该数字在两个数组中出现次数的最小值。

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

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

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

双指针:

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