My method for quickly returning an array of non-duplicates from a given unsorted array only seems to work some of the time:
public static int[] removeDuplicates(int[] arr) {
if (arr.length <= 1) {
return arr;
}
int lastFound = arr[0];
int currPos = 1;
for (int i = 1; i < arr.length; ++i) {
int num = arr[i];
if (lastFound != num) {
lastFound = num;
arr[currPos++] = num;
}
}
return Arrays.copyOf(arr, currPos);
}
When I input:
int[] arr = {0, 1, 1, 0, 1, 1, 2, 2}
int[] arr2 = removeDuplicates(arr);
it will return:
arr2 = {0, 1, 0, 1, 2}
Where it should return (with no duplicates):
arr2 = {0, 1, 2}