sourcecode

Saturday, January 5, 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].
Using the method developed in Search Insert Position
class Solution {
    pair<bool, int> process(int A[], int start, int end, int target){
        if (start == end){
            if (target > A[start]) return pair<bool, int>(false, start+1);
            else if (target < A[start]) return pair<bool, int>(false, start);
            else return pair<bool, int>(true, start);
        }
        int half = start + (end-start)/2;
        if (target <= A[half]) return process(A, start, half, target);
        else return process(A, half+1, end, target);
    }
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> r(2,-1);
        pair<bool, int> found = process(A, 0, n-1, target);
        if (!found.first) return r;
        r[0] = found.second;
        found = process(A,0,n-1,target+1);
        r[1] = found.second - 1;
        return r;
        
    }
};

No comments: