I have a problem with removig duplicate elements from an array in Java. I made two extra functions, one which counts how many unique elements there are and one which checks if the integer is already in the result array. Everything seems to work, but I fail a test where 0 is supposed to be 2nd in the array, but it's always moved to the end in my code. What can I do to fix this mistake?
Tester is showing this error:
Expected :is [<100>, <0>, <3>, <4>, <562>]
Actual :[<100>, <3>, <4>, <562>, <0>]
This is my code so far:
public static int[] removeDuplicates(int[] integers) {
int count = countUniques(integers);
int counter = 0;
int[] result = new int[count];
for (int integer : integers) {
Boolean isInArray = isInArray(result, integer);
if (!isInArray) {
result[counter] = integer;
counter++;
}
}
return result;
}
public static int countUniques(int[] integers) {
int i, j;
int count = 0;
for (i = 0; i < integers.length; ++i) {
for (j = 0; j < i; j++)
if (integers[i] == integers[j])
break;
if (i == j)
count++;
}
return count;
}
public static Boolean isInArray(int[] integers, int targetInteger) {
for (int integer : integers) {
if (targetInteger == integer) {
return true;
}
}
return false;
}
int[] result = new int[count];- theresultarray is by default filled with 0s, soisInArray(result, 0);will always returntrue. You need to approach this problem in a different way (anArrayListwould be an option. Or manually resizing the array whenever you add a new element)