数组中查找数字出现的次数(二分法)
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8 输出: 2
// 左边界
public static int searchLeft(int[] arr,int k){
int l = 0;
int r = arr.length-1;
while (l<r){
int mid = (l+r)>>1;
if(arr[mid] == k){
r = mid;
}else if(arr[mid]>k){
r = mid-1;
}else {
l = mid+1;
}
}
return r;
}
// 右边界
public static int searchRight(int[] arr,int k){
int l = 0;
int r = arr.length-1;
while (l<r){
// 每次计算取前一位整,这里加一取后一位,避免死循环
int mid = (l+r+1)>>1;
if(arr[mid] == k){
l = mid;
}else if(arr[mid]>k){
r = mid-1;
}else {
l = mid+1;
}
}
return l;
}
复制代码