I'm trying to solve an algorithm question. I need to find a single integer in an array
e.g {1,1,5,5,5,3,2,2}
output should 3 because that's the only single integer there.
So far, I created an algorithm where first I sort the array and then check whether i-1 and i+1 elements are equal and if not it means I've got the single one.
The issue is; for short input it's working fine but for long inputs I receive time-outs (it takes too long to compute so my answer is not validated).
Could you give me any 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;
}