【发布时间】:2022-07-22 17:53:16
【问题描述】:
锻炼 在两个数组的交集问题中,我们给了两个数组,我们需要打印它们的交集(公共元素)。
public class IntersectionOfTwoArrays {
private static void printIntersection(int[] arr1, int[] arr2) {
HashMap<Integer, Integer> map = new HashMap<>();
// Build the frequency map for arr1
for (int i = 0; i < arr1.length; i++) {
if (map.containsKey(arr1[i])) {
map.put(arr1[i], map.get(arr1[i]) + 1);
} else {
map.put(arr1[i], 1);
}
}
// Traverse the elements of arr2 one by one
for (int i = 0; i < arr2.length; i++) {
// If the map contains current element
if (map.containsKey(arr2[i])) {
// Reduce the frequency by 1
int freq = map.get(arr2[i]);
freq--;
// If freq becomes 0, remove the element from the map
if (freq == 0) {
map.remove(arr2[i]);
} else {
map.put(arr2[i], freq);
}
// Print the element
System.out.print(arr2[i] + " ");
}
}
System.out.println();
}
我发现这个实现对我来说非常好。 不幸的是,我不明白第二部分中删除数量的频率。
如果地图包含来自第一个数组的键,它应该有频率一,那么如果再次发生它应该去+1,为什么我们要删除存在于第一个地图中的元素?
for (int i = 0; i < arr2.length; i++) {
// If the map contains current element
if (map.containsKey(arr2[i])) {
// Reduce the frequency by 1
int freq = map.get(arr2[i]);
freq--;
// If freq becomes 0, remove the element from the map
if (freq == 0) {
map.remove(arr2[i]);
} else {
map.put(arr2[i], freq);
}
【问题讨论】:
标签: java