统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
直接写了个暴力法过了。时间On
一看答案竟然是二分法。
二分法找到左右边界,相减就是出现次数
class Solution {
public:
int search(vector<int>& nums, int target) {
//查找左边界
int l = 0, r = nums.size() - 1;
while(l <= r){
int mid = (l+r)/2;
if(nums[mid] < target){
l = mid + 1;
}
else if(nums[mid] > target){
r = mid - 1;
}
else{//如果mid = target,说明左边界是mid或者在mid左边
r = mid - 1;
}
}
int left = l;
//查找右边界
l = 0;
r = nums.size() - 1;
while(l <= r){
int mid = (l+r)/2;
if(nums[mid] < target){
l = mid + 1;
}
else if(nums[mid] > target){
r = mid - 1;
}
else{//如果mid = target,说明左边界是mid或者在mid左边
l = mid + 1;
}
}
int right = r;
//如果数组中没有target,最后left = mid, right = mid-1
return right - left + 1;
}
};