easy
给定两个数组,编写一个函数来计算他们的交集。
示例1:输入:nums1 = [1,2,2,1],nums2 = [2,2]
输出:[2]
示例2:输入:nums1 = [4,9,5],nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
*输出结果中的每个元素一定是唯一的。
*我们可以不考虑输出结果的顺序。
class Solution{
public int[] intersection(int[] nums1,int[] nums2){
//创建两个Set类型的集合
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
//将两个数组加入到Set集合中
for(int num : nums1){
set1.add(num);
}
for(int num : nums2){
set2.add(num);
}
//返回方法结果
return getIntersection(set1,set2);
}
public int[] getInterssection(Set<Integer> set1,Set<Integer> set2){
//区集合大小相对较小的那个集合
if(set1.size() > set2.size()){
return getIntersection(set2,set1);
}
//判断set2中的元素set1中是否含有
//此时新建一个set类型的集合
Set<Integer> intersectionSet = new HashSet<Integer>(set1.size() + set2.size());
int(int num : set1){
if(set2.contains(num)){
intersectionSet.add(num);
}
}
//将set集合中的元素加入到int数组中
int[] intersection = new int[intersectionSet.size()];
int index = 0;
for(int num : intersectionSet){
intersection[inndex++] = num;
}
return intersection;
}
}
思想:
首先使用两个集合分别存储两个数组中的元素,然后遍历较小的集合,判断其中的每个元素是否在另一个集合中,如果元素也在另一个集合中,则将元素添加到返回值。
因为方法为int类型,所以又创建了一个int类型的数组,将set集合中的元素添加到int数组中。
和双指针方法思想几乎相同。