难度简单330
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
本题主要考察数组去重,利用Set集合的不可重复性进行元素过滤。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {//利用Set集合的不可重复性进行元素过滤
Set<Integer> res1 = new HashSet<>();
Set<Integer> res2 = new HashSet<>();
for(int i:nums1){
res1.add(i);
}
for(int i:nums2){
if(res1.contains(i))
res2.add(i);
}
int [] ans = new int[res2.size()];
int j=0;
for(int i:res2){
ans[j++] = i;
}
return ans;
}
}