链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.empty()) return 0;
int n = nums.size() - 1;
int l = 0, r = n;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] < target) l = mid + 1;
else r = mid;
}
int left = l;
l = 0, r = n;
while (l < r) {
int mid = l + r + 1 >> 1;
if (nums[mid] <= target) l = mid;
else r = mid - 1;
}
return r - left + 1;
}
};