AcWing 67. 数字在排序数组中出现的次数
原题链接
简单
作者:
daniellee
,
2019-04-17 00:07:17
,
所有人可见
,
阅读 1229
(二分查找) $O(log(n))$
C++ 代码
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
int half = (nums.size()-1)/2;
int r = nums.size()-1;
int l = 0;
if (nums.empty()) return 0;
while(l<=r){
half = (l+r)/2;
if (nums[half]<k){
l = half + 1;
}
else if (nums[half] >= k){
r = half-1;
}
}
int cnt = 0;
int a = half+1;
int b = half;
// cout<<nums[half]<<endl;
// cout<<half<<endl;
while(k == nums[a] && a<nums.size() ) {
a++;
cnt++;
// cout<<cnt<<endl;
}
while(k == nums[b] && b>=0){
b--;
cnt++;
}
return cnt;
}
};