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

 使用二分查找先查找左边界,然后查找右边界

注意:题目假设target value一定可以找到,所以,不需要判断标记是否出界

vector<int> searchRange(vector<int>& nums, int target) {
    int beg = 0, end = nums.size() - 1, mid = 0;
    vector<int> ret = {-1, -1};
    // 查找左边界
    while (beg <= end)
    {
        mid = beg + ((end - beg) >> 1);
        if (target <= nums[mid])
            end = mid - 1;
        else
            beg = mid + 1;
    }
    
    if (nums[beg] == target)
        ret[0] = beg;
    else
        return ret;
    // 查找右边界
    end = nums.size() - 1; // 从左边界开始查找
    while (beg <= end)
    {
        mid = beg + ((end - beg) >> 1);
        if (target < nums[mid])
            end = mid - 1;
        else
            beg = mid + 1;
    }
    ret[1] = end;
    return ret;
}

 

posted @ 2015-12-15 14:12  sdlwlxf  阅读(148)  评论(0编辑  收藏  举报