可以使用HashMap来实现合并两个数组,并输出数组中两个数组都有的元素。具体步骤如下:

  1. 创建一个HashMap对象,用于存储数组中的元素。
  2. 遍历第一个数组,将数组中的元素作为键存储到HashMap中,值设为1。
  3. 遍历第二个数组,如果数组中的元素在HashMap中存在,将值设为2。
  4. 创建一个ArrayList对象,用于存储结果。
  5. 再次遍历第二个数组,如果数组中的元素在HashMap中的值为2,则将该元素添加到ArrayList中。
  6. 将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

java编程: hashmap去做合并 输出数组两个数组中都有元素则去除1233452得到145

原文地址: https://www.cveoy.top/t/topic/h69Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录