I have to write the following method:
I have sorted array of integers and in this array every integer repeats twice, except two elements. I have to find these two elements.
- Input: 1, 1, 2, 3, 3, 4, 4, 5
- Output: 2, 5
This is my solution:
private static int[] findUniques(int[] arr) {
int[] res = new int[2];
int start = 0; // start can be 0 or 1 only; it indicates the position in array res
for (int i = 0; i < arr.length-2; ) {
if(arr[i] == arr[i+1]){
i+=2;
if(i == arr.length-1){
res[1] = arr[arr.length-1];
}
}
else{
if(arr[i+1] == arr[i+2]){
res[start] = arr[i];
start++;
i+=3;
if(i == arr.length-1){
res[1] = arr[arr.length-1];
}
}
else{
res[start] = arr[i];
res[start+1] = arr[i+1];
break;
}
}
}
return res;
}
Is there a clearer way to find these two values? I don't like that I have so many if
-else
statements, but I don't know how to write it better.