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 {
private:
int left_bound(std::vector<int> &nums, int target){
int begin = 0;
int end = nums.size()-1;
while(begin<=end)
{
int mid = (begin + end)/2;
if(target == nums[mid])
{
if (mid == 0 || nums[mid-1] < target )
return mid;
end = mid - 1;
}else if(target < nums[mid])
{
end = mid - 1;
}else if(target > nums[mid])
{
begin = mid + 1;
}
}
return -1;
}
int right_bound(std::vector<int> &nums, int target){
int begin = 0;
int end = nums.size()-1;
while(begin<=end)
{
int mid = (begin + end)/2;
if(target == nums[mid])
{
if (mid == nums.size()-1 || nums[mid+1] > target )
return mid;
begin = mid + 1;
}else if(target < nums[mid])
{
end = mid - 1;
}else if(target > nums[mid])
{
begin = mid + 1;
}
}
return -1;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res(2);
res[0] = -1;
res[1] = -1;
if(nums.size()==0)
return res;
res[0] = left_bound(nums, target);
res[1] = right_bound(nums, target);
return res;
}
};