I am trying to solve an issue with an algorithm. I need to find a single integer in an array
for example {1,1,5,5,5,3,2,2}
the conclusion should be 3, because the only one whole.
So far I have created an algorithm in which I first sort the array, and then check if the elements are i-1 and i + 1, and if this does not mean that I have one.
The problem is this: for short input it works fine, but for long inputs I get timeouts (it takes too much time to calculate, so my answer is not checked).
Could you give me some tips for improving the algorithm?
static int lonelyinteger(int[] a) {
Arrays.sort(a);
if (a.length == 1)
return a[0];
for (int i = 0; i < a.length; ++i) {
if (i == 0) {
if (a[i + 1] != a[i])
return a[i];
} else if (i == a.length - 1) {
if (a[i] != a[i - 1])
return a[i];
} else {
if (a[i - 1] != a[i] && a[i + 1] != a[i])
return a[i];
}
}
return -1;
}
waff source
share