两个数组的交集
问题描述
给定两个数组 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] 也是可通过的
解题思路
使用set
代码实现
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//特殊情况处理
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
//用hashset存储nums1去掉nums1中的重复元素
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) {
set1.add (num);
}
Set<Integer> resSet = new HashSet<>();
//将nums2中与set1中相同的元素放入resSet中
for (int num : nums2) {
if (set1.contains(num))
resSet.add (num);
}
//将set转换为数组
int[] res = new int[resSet.size()];
int i = 0;
//用增强for循环取出set中的元素
for (int value : resSet) {
res[i++] = value;
}
return res;
}
}
复杂度
时间复杂度: O(n)
空间复杂度:O(n)