Given an array of integers sorted in ascending order, 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]
.
不能大意啊,以为很简单,但是处处是坑,记笔记防止再犯错。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res = {-1,-1};
if(nums.empty())
return res;
int left = 0, right = nums.size()-1;
while(left <= right)
{
int mid = left + (right - left)/2;
if(nums[mid] < target)
left = mid + 1;
else
right = mid - 1; //注意这里是nums[mid]大于等于target时
}
/*
对于nums= {-1},target=0,的情况,会得到left=1,若调用nums[left],则越界返回0,正好等于target,产生错误结果
这里一定要注意!!!
if(nums[left] != target)
res[0] = -1;
else
res[0] = left;*/
if(left >= 0 &&left < nums.size() && nums[left] == target)
res[0] = left;
else
return res;
left = 0;
right = nums.size()-1;
while(left <= right)
{
int mid = left + (right - left)/2;
if(nums[mid] <= target)
left = mid + 1;//注意这里是nums[mid]小于于等于target时
else
right = mid - 1;
}
if(nums[right] != target)
res[1] = -1;
else
res[1] = right;
return res;
}
};