思路
二次二分查找,查找target的右边界和target-1的右边界。target-1存在与否不影响边界的查找,可以理解成搜索插入位置。二者相减即为target出现的次数
class Solution {
public:
int rightBound(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = l + (r - l)/2;
if (nums[mid] == target) l = mid + 1;
else if (nums[mid] > target) r = mid - 1;
else if (nums[mid] < target) l = mid + 1;
}
return r;
}
int search(vector<int>& nums, int target) {
return rightBound(nums, target) - rightBound(nums, target-1);
}
};