java编程: hashmap去做合并 输出数组两个数组中都有元素则去除1233452得到145
可以使用HashMap来实现合并两个数组,并输出数组中两个数组都有的元素。具体步骤如下:
- 创建一个HashMap对象,用于存储数组中的元素。
- 遍历第一个数组,将数组中的元素作为键存储到HashMap中,值设为1。
- 遍历第二个数组,如果数组中的元素在HashMap中存在,将值设为2。
- 创建一个ArrayList对象,用于存储结果。
- 再次遍历第二个数组,如果数组中的元素在HashMap中的值为2,则将该元素添加到ArrayList中。
- 将ArrayList转换为数组并返回结果。
下面是Java代码实现:
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {3, 4, 5, 2};
int[] result = mergeArrays(arr1, arr2);
for (int num : result) {
System.out.print(num + " ");
}
}
public static int[] mergeArrays(int[] arr1, int[] arr2) {
HashMap<Integer, Integer> map = new HashMap<>();
// 遍历第一个数组,将元素存储到HashMap中
for (int num : arr1) {
map.put(num, 1);
}
// 遍历第二个数组,如果元素在HashMap中存在,将值设为2
for (int num : arr2) {
if (map.containsKey(num)) {
map.put(num, 2);
}
}
// 创建ArrayList对象,用于存储结果
ArrayList<Integer> list = new ArrayList<>();
// 再次遍历第二个数组,如果元素在HashMap中的值为2,则添加到ArrayList中
for (int num : arr2) {
if (map.get(num) == 2) {
list.add(num);
}
}
// 将ArrayList转换为数组并返回结果
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}
运行结果为:1 2
原文地址: https://www.cveoy.top/t/topic/h69Z 著作权归作者所有。请勿转载和采集!