How to keep zero values in an array of duplicates?

Viewed 116

I'm still struggling to get the right input for this code where I need to remove duplicates and return the result. I get everything right until this:

  • given array [100, 0, 3, 4, 4, 562, 100]

  • the answer should be [100, 0, 3, 4, 562]

  • but what I get is [100, 3, 4, 562] (So it removes the 0)

Is there any way I can just add to my code since I'm not allowed to use any built-in functions, ArrayList, List, Set etc, so just implementing my own solution and functions.

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;
}
2 Answers

withoutDubs is filled with 0s by default when it is first instantiated.

Therefore checkIfInArray(withoutDubs, 0) returns true even if 0 appears only once in the array.

You can pass an index to checkIfInArray, so that it doesn't search all the withoutDubs array. It should only check indices 0 to pos - 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;
}

and change the method call from

checkIfInArray(withoutDubs, element)

to

checkIfInArray(withoutDubs, pos, element)

Since you can't use any built-in functions, then you can implement them yourself: a kind of contains and grow methods from the ArrayList. And since the int[] array contains zeros by default, you can use the Integer[] array instead.

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;
}
Related