Find the Unique Number
Thoughts
Code
import java.util.*;
public class MyClass {
public static int findSingle(int[] nums) {
int start = 0, end = nums.length - 1;
// does not quit even start == end
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid > 0 && nums[mid] == nums[mid - 1]) {
int len = mid + 1;
if ((len & 1) == 0) {
start = mid + 1;
} else {
end = mid - 2;
}
} else if (mid + 1 < nums.length && nums[mid] == nums[mid + 1]) {
int len = mid + 2;
if ((len & 1) == 0) {
start = mid + 2;
} else {
end = mid - 1;
}
} else {
return nums[mid];
}
}
return -1;
}
public static void main(String args[]) {
int[] test1 = new int[]{7, 7, 9, 9, 8, 8, 6, 2, 2, 4, 4};
int[] test2 = new int[]{7, 7, 9, 8, 8, 6, 6, 2, 2, 4, 4};
int[] test3 = new int[]{1, 1, 2, 2, 3, 5, 5, 9, 9};
int[] test4 = new int[]{7, 7, 9, 9, 8, 8, 6, 6, 2, 2, 4};
int[] test5 = new int[]{7, 7, 9};
int[] test6 = new int[]{9, 7, 7};
int[] test7 = new int[]{9};
System.out.println("Solution: " + findSingle(test1));
System.out.println("Solution: " + findSingle(test2));
System.out.println("Solution: " + findSingle(test3));
System.out.println("Solution: " + findSingle(test4));
System.out.println("Solution: " + findSingle(test5));
System.out.println("Solution: " + findSingle(test6));
System.out.println("Solution: " + findSingle(test7));
}
}Analysis
Last updated