Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
class Solution {
public:
vector<int> searchRange(vector<int>& v, int b) {
int n=v.size();
int low=0;
int high=n-1;
int mid;
vector<int> ans(2);
ans[0]=-1;
ans[1]=-1;
while(low<=high)
{
mid=low+(high-low)/2;
if(v[mid]==b)
{
ans[0]=mid;
high=mid-1;
}
else if(v[mid]<b){
low=mid+1;
}
else{
high=mid-1;
}
}
if(ans[0]==-1) return ans;
low=ans[0];
high=n-1;
while(low<=high)
{
mid=low+(high-low)/2;
if(v[mid]==b)
{
ans[1]=mid;
low=mid+1;
}
else if(v[mid]<b){
low=mid+1;
}
else{
high=mid-1;
}
}
return ans;
}
};
Comments
Post a Comment