题目:统计一个数字在排序数组中出现的次数,例如s输入排序数组{1,2,3,3,3,3,4,5}和数字3,由于3在这个数组中出现了4次,因此输出4
算法核心:递归不断的利用二分法查找第一个3和最后一个3
private int getFistKey(int[] data,int length,int k,int start,int end){
if(start > end)
return -1;
int middleIndex = (start + end)/2;
int middleData = data[middleIndex];
if(middle == k){
if((middleIndex>0 && data[middleIndex -1] != k) || middleIndex == 0){
return middleIndex;
else
end = middleIndex -1;
}
}
else if(middleIndex >k){
end = middleIndex - 1;
}
else
start = middleIndex + 1;
return getFirstKey(data,length,k,start,end);
}
private int getLastKey(int[] data,int length,int k,int start,int end){
if(start>end){
return -1;
}
int middleIndex = (start + end)/2;
int middleData = data[middleIndex];
if(middleData == k){
if((middleIndex < length -1 && data[middleIndex+1] != k) || middleIndex == length -1){
return middleI ndex;
}
}
else if(middleData < k)
start = middleIndex +1;
else
end = middleIndex -1;
return getLastKey(data,length,k,start,end);
}
private int getNumOfKey(int[] datam int length,int k){
int num = 0;
if(data != null && lenngth >0){
int first = getFirstKey(data,length,k,0,length-1);
int last = getLastKey(data,length,k,0,length -1);
if(first > -1, && ;last > -1){
num = last - first +1;
}
}