Friday, December 26, 2014

Search for a Range

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

T:
First do binary search to find the left most position of the target, then do binary search to find the right most position.

A:


class Solution {
public:
    vector< int > searchRange(int A[], int n, int target) {
        vector< int > ret;
        ret.push_back(-1);
        ret.push_back(-1);
        int l=0;
        int r=n-1;
        while(l < r) {
            int m=(l+r)/2;
            if(A[m] < target) {
                l=m+1;
            } else {
                r=m;
            }
        }
        if(A[l] != target) {
            return ret;
        }
        int low = l;
        r=n-1;
        while(l < r) {
            int m=(l+r+1)/2;
            if(A[m] > target) {
                r=m-1;
            } else {
                l=m;
            }
        }
        if(A[r] != target) {
            return ret;
        }
        int hi = r;
        ret[0] = low;
        ret[1] = hi;
        return ret;
    }
};

No comments:

Post a Comment