Saturday, March 2, 2013

Search for a Range

/*
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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
*/
class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> result;
        result.push_back(-1);
        result.push_back(-1);
       
        if(target < A[0] || target > A[n-1]) return result;
       
        int start = 0;
        int end = n-1;
     
        int low = -1;
        int high = -1;
        int mid;
        if(A[start]==target) low = start;
        else{
          while(start <= end){
            mid = (start+end)/2;
            if(target==A[mid] && target>A[mid-1]){
              low = mid;
              break;
            }
            if(target<=A[mid]) end = mid-1;
            if(target>A[mid]) start = mid+1;
            }
        }
       
        start = 0;
        end = n-1;
        if(A[end]==target) high = end;
        else{
          while(start <= end){
            mid = (start+end)/2;
            if(target==A[mid] && target<A[mid+1]){
              high = mid;
              break;
            }
            if(target<A[mid]) end = mid-1;
            if(target>=A[mid]) start = mid+1;
            }
        }
       
        if(low!=-1 || high!=-1){
          result.clear();
          if(low!=-1){
            result.push_back(low);
          } else result.push_back(high);
          if(high!=-1){
           result.push_back(high);
          } else result.push_back(low);
        }
       
        return result;
    }
};

No comments:

Post a Comment