题目
给定两个数组 nums1 和 nums2 ,返回它们的交集 。输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序 。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的
提示:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
思路
利用Set集合的去重特性,建立2个Set集合,一个集合用来存放一个数组的元素,另一个集合用来比较过滤出2个数组之间的公共元素(去重)。
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> parentSet = new HashSet<>();
Set<Integer> childSet = new HashSet<>();
//遍历nums1数组,添加其中元素到集合parentSet中
for (int num : nums1) {
parentSet.add(num);
}
//遍历nums2数组,如果nums1集合中含nums2数组中的元素,将2个数组的公共元素加入到集合childSet中(去重)
for (int num : nums2) {
if (parentSet.contains(num)) {
childSet.add(num);
}
}
//输出2个数组的交集,即公共元素
int[] resArr = new int[childSet.size()];
int index = 0;
for (int value : childSet) {
resArr[index++] = value;
}
return resArr;
}
}