Helquin Helquin - 28 days ago 5
Java Question

How do I further optimize my code?

I'm given an array of doubles, all numbers are equal except for one. My task is to find that unique number. My code returns the correct output and now I'm wondering how will I further optimize it.

This is my code:

public static double findUnique(double array[]) {
double unique = 0;
double common = 0;

for(int i=0; i<array.length; i++) {
for(int j=i+1; j<array.length; j++) {
if(array[i]==array[j]) {
common = array[i];
}
}
if(common!=array[i]) {
unique = array[i];
}
}
return unique;
}


The only thing I could think of is storing the length of the array first, but after some testing it actually took longer. Thanks.

Answer Source
public static double findUnique(double array[]) {
    if(array.length < 3) { 
       throw new IllegalArgumentException("wrong array");
    }

    double common;
    if(array[0] == array[1]) {
       common = array[0];
    } else {
       return array[0] != array[2]? array[0]: array[1];
    }

    for(int i=2; i<array.length; i++) {
       if(common != array[i]) {
          return array[i];
       }
    }
    throw new IllegalArgumentException("wrong array"); 
}