C++ 代码
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
if(nums.empty())return 0;
if(nums.size()==1)return k==nums[0];
int len=nums.size()-1;
int l=0,r=len;
while(l<r){
int mid=(l+r)>>1;
if(nums[mid]>=k)r=mid;
else l=mid+1;
}
int li=0,ri=len;
while(li<ri){
int mid=(li+ri+1)>>1;
if(nums[mid]<=k)li=mid;
else ri=mid-1;
}
if(li==l&&l==0)return 0;
return li-l+1;
}
};