题目
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
思路
寻找右侧边界,寻找左侧边界,两次二分。注意边界的收缩。
二分总结
代码
public int search(int[] nums, int target) {
//寻找右边界
int left = 0;
int right = nums.length-1;
while(left<=right){
int mid = left+(right-left)/2;
if(nums[mid]<=target) left = mid+1;
else right = mid-1;
}
int rightcur = right;
if(right>=0&&nums[right]!=target) return 0;
//寻找左边界
left = 0;right = nums.length-1;
while(left<=right){
int mid = left+(right-left)/2;
if(nums[mid]<target) left = mid+1;
else right = mid-1;
}
int leftcur = left;
return rightcur-leftcur+1;
}