Skip to content

Instantly share code, notes, and snippets.

@kyunghoj
Last active July 8, 2016 16:07
Show Gist options
  • Save kyunghoj/59332b5c713d31c5480d16c0301b76e2 to your computer and use it in GitHub Desktop.
Save kyunghoj/59332b5c713d31c5480d16c0301b76e2 to your computer and use it in GitHub Desktop.
Find the element that appears once in a sorted array
// Divide-and-conquer
public class Find {
public static void main(String [] args) {
// int [] arr = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8};
int [] arr = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8};
int low = 0;
int high = arr.length;
if (arr.length < 3 || arr.length % 2 == 0) {
System.err.println("Input error: array must have more than 2 elements and odd numbers of elements.");
return;
}
int mid = 0;
while (low < high) {
mid = (high - low) / 2 + low;
System.out.println("log: " + "low = " + low + " mid = " + mid + " high = " + high);
if (mid == low) break;
if ( arr[mid] == arr[mid + 1] ) {
if ( mid % 2 == 0 )
low = mid + 2;
else
high = mid;
}
else if ( arr[mid] == arr[mid - 1] ) {
if ( mid % 2 == 0 )
high = mid - 1;
else
low = mid + 1;
}
}
System.out.println("arr[" + low + "] = " + arr[low]);
return;
}
}

Given a sorted array in which all elements appear twice (one after one) and one element appears only once. Find that element in O(log n) complexity.

Example:

Input:   arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}
Output:  4

Input:   arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8}
Output:  8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment