题目描述
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 ofO(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].
分析:使用二分查找,查找左右边界即可
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res(2,-1);
if(A==nullptr || n<=0)
return res;
int low = 0,high = n-1;
while(low<=high)
{
int middle = (high+low)>>1;
if(A[middle] < target) /// 向左夹逼,则找到左边界
low = middle+1;
else
high = middle-1;
}
int low2 = 0,high2 = n-1;
while(low2 <=high2)
{
int middle2 = (high2+low2)>>1;
if(A[middle2] <= target) /// 向右夹逼,找到右边界
low2 = middle2+1;
else
high2 = middle2-1;
}
if(low <= high2)
{
res[0] = low;
res[1] = high2;
}
return res;
}
};