Monday, November 25, 2013

LeetCode Problem : Search for a Range

Problem


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].

Code

int bin_search(int A[],int l,int r,int target)
{
    if(l == r)
    {
        if(A[l - 1] == target)
            return l - 1;
        return -1;
    }
    if(l > r)
        return -1;
        int mid = (l + r)/2;
        if(target == A[mid - 1]){
        return mid - 1;
    }
    else if(target > A[mid - 1])
        return bin_search(A,mid + 1,r,target);
    else
        return bin_search(A,l,mid - 1,target);
}
vector<int> searchRange(int A[], int n, int target) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    vector<int> result;
    int ret = 0;
    int l = 1,r = n;
    int lb = -1,ub = -1;
    int pos = r;
    while(pos > 0 && (ret = bin_search(A,l,pos,target)) != -1){
        lb = ret;
        pos = ret;
    }
    pos = l;
    while( pos <= n && (ret = bin_search(A,pos,r,target)) != -1){
        ub = ret;
        pos = ret + 2;
    }
    result.push_back(lb);
    result.push_back(ub);
    return result;
}

No comments:

Post a Comment