1

我仍在努力为此代码获取正确的输入,我需要删除重复项并返回结果。在此之前,我一切正常:

  • 给定数组[100, 0, 3, 4, 4, 562, 100]

  • 答案应该是[100, 0, 3, 4, 562]

  • 但我得到的是[100, 3, 4, 562](所以它删除了 0)

有什么办法可以添加到我的代码中,因为我不允许使用任何内置函数、ArrayList、List、Set 等,所以只需实现我自己的解决方案和函数。

public static int[] removeDuplicates(int[] input) {
    int[] withoutDubs = new int[input.length];
    int pos = 0;
    for(Integer element: input) {
        if(!checkIfInArray(withoutDubs, element)) {
            withoutDubs[pos] = element;
            pos++;
        }
    }
    int[] result = new int[pos];
    for(int i = 0; i < pos; i++) {
        result[i] = withoutDubs[i];
    }
    return result;
}

public static boolean checkIfInArray(int[] input, int number) {
    if(input == null) {
        return false;
    }
    for(Integer num: input) {
        if(num == number) {
            return true;
        }
    }
    return false;
}
4

2 回答 2

3

withoutDubs第一次实例化时默认填充0。

因此即使在数组中只出现一次也checkIfInArray(withoutDubs, 0)返回。true0

您可以将索引传递给checkIfInArray,以便它不会搜索所有withoutDubs数组。它应该只检查索引0pos - 1.

public static boolean checkIfInArray(int[] input, int last, int number) {
    if(input == null) {
        return false;
    }
    for(int i = 0; i < last; i++) {
        if(input[i] == number) {
            return true;
        }
    }
    return false;
}

并将方法调用从

checkIfInArray(withoutDubs, element)

checkIfInArray(withoutDubs, pos, element)
于 2021-02-18T09:14:40.313 回答
1

既然你不能使用任何内置函数contains,那么你可以自己实现它们:一种grow来自ArrayList. 由于int[]数组默认包含,因此您可以改用Integer[]数组。

public static void main(String[] args) {
    int[] arr = {100, 0, 3, 4, 4, 562, 100};
    Integer[] noDuplicates = new Integer[0];

    for (int i = 0, j = 0; i < arr.length; i++) {
        if (!contains(noDuplicates, arr[i])) {
            noDuplicates = grow(noDuplicates);
            noDuplicates[j++] = arr[i];
        }
    }

    // output: [100, 0, 3, 4, 562]
    System.out.println(Arrays.toString(noDuplicates));
}
static boolean contains(Integer[] arr, int val) {
    for (Integer el : arr) {
        if (el != null && el == val) {
            return true;
        }
    }
    return false;
}
static Integer[] grow(Integer[] arr) {
    Integer[] target = new Integer[arr.length + 1];
    System.arraycopy(arr, 0, target, 0, arr.length);
    return target;
}
于 2021-04-05T05:24:54.337 回答