Given an array of integers nums
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]
.
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target)
{
int left=0,n=nums.size(),right=n-1;
vector<int> result;
result.push_back(-1);
result.push_back(-1);
while(left<=right)
{
int mid=(left+right)/2;
if(target>nums[mid])
left=mid+1;
else if(target<nums[mid])
right=mid-1;
else
{
result[0]=mid;
result[1]=mid;
int j=mid-1;
while(j>=0&&nums[j]==target)
{
result[0]=j;
j--;
}
int k=mid+1;
while(k<=n-1&&nums[k]==target)
{
result[1]=k;
k++;
}
break;
}
}
return result;
}
};