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]
.
Subscribe to see which companies asked this question
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
while(left<right)
{
int mid = (right-left)/2+left;
if(nums[mid]<target) left=mid+1;
else right=mid;
}
int ii=target==nums[left]?left:-1;
right=nums.size()-1;
if(ii==right) return {ii,ii};
while(left<right)
{
int mid = (right-left)/2+left;
if(nums[mid]<(target+1)) left=mid+1;
else right=mid;
}
int jj=-1;
if(nums[left]==target)
{
jj=left;
}
else if(nums[left-1]==target)
{
jj=left-1;
}
return {ii,jj};
}
};