class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashSet<Integer> set1= new HashSet<Integer>();
for (Integer n : nums1)
set1.add(n);
HashSet<Integer> set2 = new HashSet<Integer>();
for (Integer n : nums2)
set2.add(n);
set1.retainAll(set2);
int[] output = new int[set1.size()];
int idx=0;
for(int s :set1)
output[idx++]=s;
return output;
}
}
输出
Input:
[1,2,2,1]
[2,2]
Output:
[2]
Expected:
[2,2]
答案 0 :(得分:0)
集合不允许重复,因此如果您希望输出包含重复项,则它们不适合。
您可以使用Map<Integer,Integer>
来计算第一个数组中每个元素的出现次数,然后对照第二个数组检查它们:
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map1 = new HashMap<>();
for (int n : nums1) {
if (map1.containsKey(n))
map1.put(n,map1.get(n)+1);
else
map1.put(n,1);
}
List<Integer> inter = new ArrayList<>();
for (int n : nums2) {
Integer count = map1.get(n);
if (count != null && count > 0) {
map1.put(n,count-1);
inter.add(n);
}
}
int[] output = new int[inter.size()];
for(int i = 0; i < inter.size(); i++)
output[i]=inter.get(i);
return output;
}