私以为很简明的二分hhh
class Solution {
public:
int getNumberOfK(vector<int>& nums , int k) {
int l = 0, r = nums.size() - 1;
int cnt = 0;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == k) {
cnt++;
for(int i = m - 1; i >= l; i--)
if (nums[i] == k) cnt++;
else break;
for (int j = m + 1; j <= r; j++)
if (nums[j] == k) cnt++;
else break;
break;
}
else if (nums[m] < k) l = m + 1;
else r = m - 1;
}
return cnt;
}
};