题目:统计一个数字在排序数组中出现的次数。例如输入输入排序数组{1,2,3,3,4,5}和数字3,输出2.
思路:使用二分查找法,时间复杂度O(logN)
package offer;
/**
* 统计一个数字在排序数组中出现的次数。
* 二分查找法,时间复杂度O(logN)
* @author zhangqd
*
*/
public class GetNumberOfK {
public static void main(String[] args) {
int[] arr={1,2,3,4,4,5};
System.out.println(getNumberOfK(arr,4));
}
public static int getNumberOfK(int[] arr, int k){
int number = 0;
if(arr!=null && arr.length>0){
int first = getFirstK(arr,0,arr.length-1,k);
int last = getLastK(arr,0,arr.length-1,k);
if(first>-1 && last>-1)
number = last-first+1;
}
return number;
}
private static int getFirstK(int[] arr,int start, int end, int k){
if(start>end)
return -1;
int mid = (start+end)/2;
int midData=arr[mid];
if(midData==k){
if((mid>0 && arr[mid-1]!=k)||mid==0)
return mid;
else
end=mid-1;
}else if(midData>k){
end=mid-1;
}else
start = mid+1;
return getFirstK(arr,start,end,k);
}
private static int getLastK(int[] arr, int start, int end, int k){
if(start>end)
return -1;
int mid = (start+end)/2;
int midData = arr[mid];
if(midData==k){
if((mid<end &&arr[mid+1]!=k)|| mid==end)
return mid;
else
start = mid+1;
}else if(midData<k)
start=mid+1;
else
end=mid-1;
return getLastK(arr,start,end,k);
}
}