首页 > 解决方案 > 如何在重复数组中保持零值?

问题描述

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

有什么办法可以添加到我的代码中,因为我不允许使用任何内置函数、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;
}

标签: javaarraysduplicatesinteger

解决方案


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)

推荐阅读