文章目录
题目描述
给定两个数组,编写一个函数来计算它们的交集。
示例1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序。
题解
集合去重法(java)
思路:分别将两个数组中的数组放在集合中,从而完成去重工作,然后用到内置函数set.retainAll()
可以将剔除set中和输入集合有重复的部分。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num1 : nums1) set1.add(num1);
for (int num2 : nums2) set2.add(num2);
set1.retainAll(set2);
int[] ans = new int[set1.size()];
int index = 0;
for(int num : set1) ans[index++] = num;
return ans;
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
集合去重法2(java)
思路:思路还和上面类似,写法上:当父集合有该元素时,则不在子集合中添加,最后直接输出子集合的值。比上面的写法更快一点。
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<>();
for (int num : nums1) {
parentSet.add(num);
}
for (int num : nums2) {
if (parentSet.contains(num)) {
childSet.add(num);
}
}
int[] resArr = new int[childSet.size()];
int index = 0;
for (int value : childSet) {
resArr[index++] = value;
}
return resArr;
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度: