题目描述
blablabla
样例
blablabla
算法1
(二分查找左右端点) $O(logn)$
blablabla
时间复杂度
参考文献
C++ 代码
class Solution {
public:
int getNumberOfK(vector<int>& nums, int k) {
if (nums.empty()) return 0;
int l = 0, r = nums.size() - 1;
while (l < r){
int mid = (l + r) >> 1;
if (nums[mid] < k) l = mid + 1;
else r = mid;
}
if (nums[l] != k) return 0;
int left = l;
l = 0, r = nums.size() - 1;
while (l < r){
int mid = (l + r + 1) >> 1;
if (nums[mid] <= k) l = mid;
else r = mid - 1;
}
if (nums[r] != k) return 0;
return r - left + 1;
}
};
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla