题目链接

题目描述

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

示例 1:

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

示例 2:

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

思路

思路 1

image.png
转成 set 直接调用内置函数

  1. public int[] intersection(int[] nums1, int[] nums2) {
  2. // boxed 的作用就是将 int类型的stream 转成了 Integer 类型的 Stream
  3. Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
  4. // 转成 intString
  5. return Arrays.stream(nums2).distinct().filter(set::contains).toArray();
  6. }

不采用内置函数

  1. public int[] intersection(int[] nums1, int[] nums2) {
  2. Set<Integer> set1 = new HashSet<>();
  3. Set<Integer> set2 = new HashSet<>();
  4. for (int num : nums1) {
  5. set1.add(num);
  6. }
  7. for (int num : nums2) {
  8. set2.add(num);
  9. }
  10. return getIntersection(set1, set2);
  11. }
  12. public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
  13. // 换一下位置
  14. if (set1.size() > set2.size()) {
  15. return getIntersection(set2, set1);
  16. }
  17. // 找出交集
  18. Set<Integer> intersectionSet = new HashSet<>();
  19. for (int num : set1) {
  20. if (set2.contains(num)) {
  21. intersectionSet.add(num);
  22. }
  23. }
  24. // 把交集转成返回结果
  25. int[] intersection = new int[intersectionSet.size()];
  26. int index = 0;
  27. for (int num : intersectionSet) {
  28. intersection[index++] = num;
  29. }
  30. return intersection;
  31. }

复杂度分析

image.png

思路 2

去重排序后,比较大小,如果一致则加入,否则小的那条数组指针后移,直到到一个链表末尾(去重和排序其实也是调用内置函数。。。)

image.png

  1. public int[] intersection(int[] nums1, int[] nums2) {
  2. Arrays.sort(nums1);
  3. Arrays.sort(nums2);
  4. int length1 = nums1.length;
  5. int length2 = nums2.length;
  6. int[] intersection = new int[length1 + length2];
  7. int index = 0, index1 = 0, index2 = 0;
  8. while (index1 < length1 && index2 < length2) {
  9. int num1 = nums1[index1];
  10. int num2 = nums2[index2];
  11. // 相等,加入元素,然后同时移动
  12. // 否则小的移动
  13. if (num1 == num2) {
  14. // 保证加入元素的唯一性
  15. if (index == 0 || num1 != intersection[index - 1]) {
  16. intersection[index++] = num1;
  17. }
  18. index1++;
  19. index2++;
  20. } else if (num1 < num2) {
  21. index1++;
  22. } else {
  23. index2++;
  24. }
  25. }
  26. return Arrays.copyOfRange(intersection, 0, index);
  27. }