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;
}
CodePudding user response:
When you create a primitive int
array it is by default filled with 0s. You can change your code to use an Integer
object array. That way the default value for each element will be null.
You would then need to null check each element inside your isInArray()
:
public static Boolean isInArray(Integer[] integers, int targetInteger) {
for (Integer integer : integers) {
if (integer != null && targetInteger == integer) {
return true;
}
}
return false;
}
And change your result
array to Integer[] result = new Integer[count];
and return Integer[] instead of int[].
If you want to return primitive array you can use streams and map Integer to int.
something like
return Arrays.stream(result).mapToInt(i-> i).toArray();
CodePudding user response:
You haven't filled up the result array yet, so the end of it will be filled with zeros. You only want to loop over the part that you have filled. One way to achieve this is to pass the value of counter to your isInArray
method.
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, counter, 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 integersLength, int targetInteger) {
for (int i = 0; i < integersLength; i ) {
if (targetInteger == integers[i]) {
return true;
}
}
return false;
}