AcWing 67. 数字在排序数组中出现的次数C++
原题链接
简单
作者:
沙漠绿洲
,
2020-08-22 16:22:15
,
所有人可见
,
阅读 500
两次二分,找到上下界即可
C++ 代码
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
if(nums.empty()) return 0;
int l = 0, r = nums.size() - 1, ret = 0;
while(l < r){//二分找下界
int mid = l + r >> 1;
if(nums[mid] < k) l = mid + 1;
else r = mid;
}
if(nums[l] != k) return 0;
ret = l;
l = 0, r = nums.size() - 1;
while(l < r){//二分找上界
int mid = l + r + 1 >> 1;
if(nums[mid] > k) r = mid - 1;
else l = mid;
}
ret = l - ret + 1;
return ret;
}
};