首页 > 解决方案 > JAVA - 比较两个数组并创建一个仅包含第一个唯一值的新数组

问题描述

我必须使用以下标准解决一个练习:

比较两个数组:

int[] a1 = {1, 3, 7, 8, 2, 7, 9, 11};
int[] a2 = {3, 8, 7, 5, 13, 5, 12};

array int[]仅使用第一个数组中的唯一值创建一个新的。结果应如下所示:int[] result = {1,2,9,11};

注意:我不允许使用ArrayListArrays类来解决此任务。

我正在使用以下代码,但填充循环的逻辑不正确,因为它引发了越界异常。

public static int[] removeDups(int[] a1, int[] a2) {
    //count the number of duplicate values found in the first array
    int dups = 0;
    for (int i = 0; i < a1.length; i++) {

        for (int j = 0; j < a2.length; j++) {
            if (a1[i] == a2[j]) {
                dups++;
            }
        }
    }
    //to find the size of the new array subtract the counter from the length of the first array
    int size = a1.length - dups;
    //create the size of the new array
    int[] result = new int[size];

    //populate the new array with the unique values
    for (int i = 0; i < a1.length; i++) {
        int count = 0;
        for (int j = 0; j < a2.length; j++) {
            if (a1[i] != a2[j]) {
                count++;
                if (count < 2) {
                    result[i] = a1[i];
                }
            }
        }
    }

    return result;
}

我也很想用一个潜在的循环(学习目的)来解决这个问题。

标签: javaarrays

解决方案


我提供以下解决方案。

  1. 遍历第一个数组,找出最小值最大值
  2. 创建长度为max-min+1 的临时数组(您可以使用max + 1作为长度,但是当您有值(例如从 100k 开始)时,它可能会产生开销)。
  3. 迭代第一个数组并标记临时数组中存在的值。
  4. 遍历第二个数组并取消标记临时数组中存在的值。
  5. 将临时数组中的所有标记值放入结果数组中。

代码:

public static int[] getUnique(int[] one, int[] two) {
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for (int i = 0; i < one.length; i++) {
        min = one[i] < min ? one[i] : min;
        max = one[i] > max ? one[i] : max;
    }

    int totalUnique = 0;
    boolean[] tmp = new boolean[max - min + 1];

    for (int i = 0; i < one.length; i++) {
        int offs = one[i] - min;
        totalUnique += tmp[offs] ? 0 : 1;
        tmp[offs] = true;
    }

    for (int i = 0; i < two.length; i++) {
        int offs = two[i] - min;

        if (offs < 0 || offs >= tmp.length)
            continue;
        if (tmp[offs])
            totalUnique--;
        tmp[offs] = false;
    }

    int[] res = new int[totalUnique];

    for (int i = 0, j = 0; i < tmp.length; i++)
        if (tmp[i])
            res[j++] = i + min;

    return res;
}

推荐阅读