349. 两个数组的交集 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/intersection-of-two-arrays/用两个Set,第一个Set保存第一个数组的元素,第二个保存结果。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> s1 = new HashSet<>();
Set<Integer> s2 = new HashSet<>();
for(int i:nums1)
s1.add(i);
for(int i:nums2){
if(s1.contains(i))
s2.add(i);
}
int [] result = new int[s2.size()];
Iterator<Integer> it = s2.iterator();
for(int i=0; it.hasNext();i++){
result[i]=it.next();
}
return result;
}
}