代码随想录学习-两个数组的交集0509
学习笔记,侵删!
1、题目:349. 两个数组的交集
题意:给定两个数组,编写一个函数来计算它们的交集。
说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。
2、题解
import java.util.HashSet; // HashSet 底层是使用了哈希表来支持的,特点: 存取速度快.
import java.util.Set; // Set 如果是实现了Set接口的集合类,具备的特点: 无序,不可重复。
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> set1 = new HashSet<>(); // 该容器中只能存储不重复的对象。
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
int[] resArr = new int[resSet.size()];
int index = 0;
//将结果几何转为数组
for (int i : resSet) {
resArr[index++] = i;
}
return resArr;
}
}
上一篇:
通过多线程提高代码的执行效率例子
