Sunday, 17 July 2016

Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example: Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

 int first(int *arr, int low, int high, int x){  
   int mid;  
   if(low > high){  
     return -1;  
   }  
   mid = low + (high - low) / 2;  
   if(arr[mid] == x && (mid == 0 || arr[mid - 1] < x )){  
     return mid;  
   } else if(arr[mid] >= x){  
     return first(arr, low, mid - 1, x);  
   }else{  
     return first(arr, mid + 1, high, x);  
   }  
 }  
 int last(int *arr, int low, int high, int x){  
   int mid;  
   if(low > high){  
     return -1;  
   }  
   mid = low + (high - low) / 2;  
   if(arr[mid] == x && (mid == high || arr[mid + 1] > x)){  
     return mid;  
   } else if(arr[mid] > x){  
     return last(arr, 0, mid - 1, x);  
   }else{  
     return last(arr, mid + 1, high, x);  
   }  
 }  
 void countOccurrences(int *arr, int n, int x){  
   int firstIndex = first(arr, 0, n - 1, x);  
   int lastIndex = last(arr, 0, n - 1, x);  
   cout << firstIndex << " " << lastIndex << endl;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive