题目描述
给定两个数组,编写一个函数来计算它们的交集。
示例 1 :
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
我的解法
思路
设置一个长度为10的数组a,存储数组nums1中是否有0-9,有的话将其置1,然后再遍历nums2,a中等于1且对应位置设为为2,最后输出数组a中等于2的索引
报错:
原来数组里并不是只有0-9的数字,那这种方法显然是不行了
那其实可以暴力求解,遍历1中的元素判断2中是否存在,时间复杂度是O(m*n) m和n分别是两个数组的长度,这里就不放代码了
更优解法
思路
主要学习Java中HashSet的写法
对应Java代码
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;
}
复杂度分析
时间复杂度:O(m+n) m和n分别是两个数组的长度
空间复杂度:O(m+n)
收获总结
HashSet.add可以使用哈希函数自动将值映射为索引,
HashSet.contain可以快速判断当前集合是否包含某一元素
有关Java中哈希表的数据结构后续会做个总结,单独放一个链接