AcWing 67. 数字在排序数组中出现的次数--二分左右模版
原题链接
简单
作者:
Jocelin
,
2021-03-16 21:58:23
,
所有人可见
,
阅读 175
经典二分左右模版方法logn复杂度
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
int left_index = getLeft(nums,k,0,nums.size());
int right_index = getRight(nums,k,left_index,nums.size());
return right_index - left_index + 1;
}
int getLeft(vector<int>& nums,int target, int left,int right)
{
while(left < right)
{
int mid = (left + right )/2;
if( target == nums[mid] )
right = mid;
else if( target > nums[mid])
left = mid+1;
else
right = mid;
}
return left;
}
int getRight(vector<int>& nums,int target, int left,int right)
{
while(left < right)
{
int mid = (left + right )/2;
if( target == nums[mid] )
left = mid+1;
else if( target > nums[mid])
left = mid+1;
else
right = mid;
}
return left -1;
}
};