leetcode 两个数组的交集 349

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
30
31
32
33
34
35
36
37
38
39
import java.util.HashSet;
import java.util.Set;

//两个数组的交集
public class IntersectionOfTwoArrays349 {
public static void main(String[] args) {
int[] arr01 = {1,2,2,6,7,4};
int[] arr02 = {2,2,5,6};
int[] intersectionArr = new Solution().intersection(arr01,arr02);
for (int item : intersectionArr) {
System.out.print(item + "\t");
}

}
}

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//安全性检验
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[]{0};
}
//先把 nums1 存起来
Set<Integer> set01 = new HashSet<>();
Set<Integer> same = new HashSet<>();

for (int item : nums1) {
set01.add(item);
}

//把 num2 拿来比
for(int item : nums2) {
if (set01.contains(item)) {
same.add(item);
}
}
return same.stream().mapToInt(Integer::intValue).toArray();
}
}

最后这个

return same.stream().mapToInt(Integer:intValue).toArray();

需要记一下。