首页 > 代码库 > leetcode:Search for a Range

leetcode: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的下标范围

vector<int> searchRange(int A[], int n, int target) {    int l,r,mid;    std::vector<int> ans;    l=0;    r=n-1;    //找到第一个不小于target的位置    while (l<=r)    {        mid=(l+r)>>1;        if (A[mid]>=target)            r=mid-1;        else l=mid+1;    }    if (A[l]==target)        ans.push_back(l);    else{        ans.push_back(-1);        ans.push_back(-1);        return ans;    }    l=0;    r=n-1;    //找到第一个大于target的位置    while (l<=r)    {        mid=(l+r)>>1;        if (A[mid]>target)            r=mid-1;        else l=mid+1;    }    ans.push_back(l-1);    return ans;}

leetcode:Search for a Range