patternjavaMinor
Find two unique integers in sorted array
Viewed 0 times
uniquearraytwofindsortedintegers
Problem
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.
This is my solution:
Is there a clearer way to find these two values? I don't like that I have so many
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.Solution
For each number in the list, either
there is no next (at end of src list) - add to result list
there is no next (at end of src list) - add to result list
- the next is different - add to the result list, increment result count (if all answers found, return)
- the next is the same; skip next, (add 2 to src pointer)
public int[] findUnique(int[] src){
int[] res = new int[2];
int resIdx = 0;
for(int i = 0; i < src.length;){
// at the end of the list, or next is different
if(i == src.length-1 || src[i] != src[i+1]){
res[resIdx++] = src[i++];
if (resIdx== 2) break;
} else{
// not different; skip next item
i+=2;
}
}
return res;
}Code Snippets
public int[] findUnique(int[] src){
int[] res = new int[2];
int resIdx = 0;
for(int i = 0; i < src.length;){
// at the end of the list, or next is different
if(i == src.length-1 || src[i] != src[i+1]){
res[resIdx++] = src[i++];
if (resIdx== 2) break;
} else{
// not different; skip next item
i+=2;
}
}
return res;
}Context
StackExchange Code Review Q#56341, answer score: 8
Revisions (0)
No revisions yet.