主要思路二分查找到K的位置 , 然后再计算有几个K
注意边界情况处理 , 以及是小于还是小于等于
public int GetNumberOfK(int [] array , int k) {
int len = array.length;
if (len == 0|| array == null){
return 0;
}
int left = 0;
int right = len -1;
int kTh = 0;
while (left<=right){
int mid = left + (right -left)/2;
int num = array[mid];
if (num == k){
if(mid == 0){
kTh = mid;
break;
}
while (left>=0&&(mid>=0)&&(mid-1>=0)&&array[mid] == array[--mid]);
kTh = mid>0?mid+1:mid;
break;
}else if (k<num){
right =mid-1;
}else if (k>num){
left = mid+1;
}
}
int count = 0 ;
int i = kTh;
while (i<=len-1&&array[i] == k){
count++;
i++;
}
return count;
}
}