LeetCode349-两个数组的交集

题目链接

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

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

题目详述

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

示例 1:

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

示例 2:

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

说明:

  • 输出结果中的每个元素一定是唯一的。
  • 我们可以不考虑输出结果的顺序。

题目详解

本题是计算两个数组的交集,并且输出结果的每一个元素一定是唯一的,不考虑输出结果的顺序,有很多种解法。

方法一:运用双指针

  • 先对两个数组进行排序。
  • 再运用双指针遍历两个数组,将交集中的元素加入到 HashSet 中。加入到 HashSet 是为了去重。
  • 最后进行转换返回。
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_00349 {

public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
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 {
set.add(nums1[i]);
++i;
++j;
}
}
int[] res = new int[set.size()];
i = 0;
for (int num : set) {
res[i++] = num;
}
return res;
}
}

方法二:运用 Set 的 contanins 方法进行查找。

  • 将一个数组中的元素加入到 Set。
  • 在遍历另一个数组的过程中进行判断,是否将其加入交集集合中。
  • 最后进行转换返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class LeetCode_00349 {

public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> interset = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
for (int num : nums2) {
if (set.contains(num)) {
interset.add(num);
}
}
int[] res = new int[interset.size()];
int i = 0;
for (int num : interset) {
res[i++] = num;
}
return res;
}
}

方法三:运用 retainAll 对两个 set 取交集。

  • List 和 Set 中均存在方法 boolean retainAll(Collection<?> c); 用来取交集。
  • 可以先将两个数组转换为 Set,再对两个 Set 取交集即可。
  • 最后进行转换返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class LeetCode_00349 {

public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> interset = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
for (int num : nums2) {
interset.add(num);
}
interset.retainAll(set);
int[] res = new int[interset.size()];
int i = 0;
for (int num : interset) {
res[i++] = num;
}
return res;
}
}