统计一个数字在排序数组中出现的次数。
思路:基于二分查找复杂度为 O(logn);二分查找开始位置,二分查找结尾位置,做差。个人感觉考察点为二分查找的灵活运用。
public class Solution {
public int GetNumberOfK(int[] array, int k) {
int firstK=getFirstK(array,k,0,array.length-1);
int lastK=getLastK(array,k,0,array.length-1);
// System.out.println(firstK);
// System.out.println(lastK);
if(firstK!=-1&&lastK!=-1){
return lastK-firstK+1;
}
return 0;
}
private int getLastK(int[] array, int k, int start, int end) {
if(start>end) {
return -1;
}
int len=array.length;
int mid=(start+end)/2;
if (array[mid]>k){
return getLastK(array,k,start,mid-1);
}else if (array[mid]<k){
return getLastK(array,k,mid+1,end);
}else if (mid+1<len&&array[mid+1]==k){
return getLastK(array,k,mid+1,end);
}else{
return mid;
}
}
//循环判断式写法
private int getFirstK(int[] array, int k, int start, int end) {
int mid=(start+end)/2;
while (start<=end){
if (array[mid]<k){
start=mid+1;
}else if(array[mid]>k){
end=mid-1;
}else if(mid-1>=0&&array[mid-1]==k){
end=mid-1;
}else{
return mid;
}
mid=(start+end)/2;
}
return -1;
}
}