英文:
Given two arrays, write a function to compute their intersection
问题
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;
}
}
output
Input:
[1,2,2,1]
[2,2]
Output:
[2]
Expected:
[2,2]
英文:
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;
}
}
output
Input:
[1,2,2,1]
[2,2]
Output:
[2]
Expected:
[2,2]
答案1
得分: 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;
}
英文:
Sets don't allow duplicates, so they are not suitable if you expect the output to contain duplicates.
You can use a Map<Integer,Integer>
to count the occurrences of each element of the first array, and then check them against the second array:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论