Reputation: 188
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.
Upvotes: 2
Views: 111
Reputation: 215
I belive that it is uneccesary to grab two new numbers in everey iteration.
Instead we could just start by grabbing the two first numbers of the array and then if those numbers are the same, we may compare the rest of the numbers to their value. So we define our common above the for loops, that way we will avoid the for loop and if statement containing: common= array[i] in every iteration. I belive this should make a difference in speed, at least if the array is crazy big.^^
Also, put the return inside the for loops so that you don't iterate the entire list even though you really found that piece of gold :):). (returning something always breaks the entire method.)
Hope I din't missunderstand anything :). Here's some code for you aswell. :)
public static double findUnique(double array[]) {
double common = 0;
if(array.length<3){
throw new IllegalArgumentException("Only two numbers exsists");
}
// Set up the common number seperately here.
if(array[0] == array[1]){
common = array[0];
}
else if(array[1] == array[2]){
return array[0];
}else{
return array[1];
}
// Now we iterate with return inside the for loop.
for(int i=2; i<array.length; i++) {
if(common!=array[i]) {
return array[i];
}
}
throw new IllegalArgumentException("All numbers are identical");
}
Upvotes: 2
Reputation: 564
What if you sort the entire array first. Then just look at the first two and one last elements of the array.
Upvotes: 0
Reputation: 60094
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");
}
Upvotes: 3