public class Solution {
public int GetNumberOfK(int [] array , int k) {
if(array ==null || array.length ==0){
return 0;
}
int firstK= getFirstK(array, 0, array.length-1, k);
int lastK= getLastK(array, 0, array.length-1, k);
if(firstK <0 || lastK<0){
return 0;
}
return lastK - firstK +1;
}
public int getFirstK(int [] array, int left, int right , int k ){
if(left > right){
return -1;
}
int mid = (left + right)/2;
if(array[mid] == k){
if(mid -1 >= 0 && array[mid-1] == k){
right = mid-1;
}else{
return mid;
}
}else if(array[mid]>k){
right = mid -1;
}else{
left = mid+1;
}
return getFirstK(array, left, right, k);
}
public int getLastK(int [] array, int left , int right , int k){
if(left > right){
return -1;
}
int mid = (left + right)/2;
if(array[mid] == k){
if(mid +1 <= array.length-1 && array[mid+1] == k){
left = mid+1;
}else{
return mid;
}
}else if(array[mid]>k){
right = mid -1;
}else{
left = mid+1;
}
return getLastK(array, left, right, k);
}
}
统计一个数字在排序数组中出现的次数
最新推荐文章于 2020-05-20 19:37:52 发布