可以使用以下方法查找两个数组中不同的值:

  1. 使用嵌套循环遍历第一个数组的每个元素,并在第二个数组中查找是否存在相同的元素。如果不存在,则将该元素添加到结果集中。
public static List<Integer> findDifferentValues(int[] arr1, int[] arr2) {
    List<Integer> result = new ArrayList<>();

    for (int i = 0; i < arr1.length; i++) {
        boolean found = false;

        for (int j = 0; j < arr2.length; j++) {
            if (arr1[i] == arr2[j]) {
                found = true;
                break;
            }
        }

        if (!found) {
            result.add(arr1[i]);
        }
    }

    return result;
}
  1. 使用哈希表来存储第一个数组中的元素,并遍历第二个数组,检查每个元素是否存在于哈希表中。如果不存在,则将该元素添加到结果集中。
public static List<Integer> findDifferentValues(int[] arr1, int[] arr2) {
    List<Integer> result = new ArrayList<>();
    Map<Integer, Integer> map = new HashMap<>();

    // 将第一个数组中的元素添加到哈希表中
    for (int i = 0; i < arr1.length; i++) {
        map.put(arr1[i], 1);
    }

    // 遍历第二个数组,检查每个元素是否存在于哈希表中
    for (int i = 0; i < arr2.length; i++) {
        if (!map.containsKey(arr2[i])) {
            result.add(arr2[i]);
        }
    }

    return result;
}

以上两种方法的时间复杂度均为O(n^2),其中n为两个数组的长度。如果数组很大,可以考虑使用排序和双指针等更高效的方法来查找不同的值。

Java 查找两个数组中不同的值:高效算法和代码示例

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

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