Difficulty: Medium
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]
.
class Solution {
int my_lowerBound(vector<int> &nums,int target){
int left =0;
int right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target){
if(mid==0||nums[mid-1]!=target)
return mid;
else
right=mid-1;
}
else if(nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
return -1;
}
int my_upperBound(vector<int> &nums,int target){
int left =0;
int size=nums.size();
int right=size-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==target){
if(mid==size-1||nums[mid+1]!=target)
return mid;
else
left=mid+1;
}
else if(nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
return -1;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
return {my_lowerBound(nums,target),my_upperBound(nums,target)};
}
};