# 剑指Offer解题报告(Java版)——排序数组中某个数的个数 38

int getLastK(int[] data,int length,int k,int start,int end){

if (start>end) {

return -1;

}

int midIndex=(start+end)/2;

int midData=data[midIndex];

if (data[midIndex]==k) {

if( (midIndex<length-1&&data[midIndex+1]!=k)||midIndex==length-1) {

return midIndex;

}else {

start=midIndex+1;

}

}else if (midData<k) {

start=midIndex+1;

}else {

end=midIndex-1;

}

return getLastK(data,length,k,start,end);

}

int getFirstK(int[] data,int length,int k,int start,int end){

if (start>end) {

return -1;

}

int midIndex=(start+end)/2;

int midData=data[midIndex];

if (data[midIndex]==k) {

if( (midIndex>0&&data[midIndex-1]!=k)||midIndex==0) {

return midIndex;

}else {

end=midIndex-1;

}

}else if (midData>k) {

end=midIndex-1;

}else {

start=midIndex+1;

}

return getFirstK(data,length,k,start,end);

}

int getNumOfK(int[] data,int length,int k){

int result = 0;

if (data!=null&&length>0) {

int first=getFirstK(data, length, k, 0, length-1);

int last=getLastK(data, length, k, 0, length-1);

System.out.println(first);

System.out.println(last);

if (first>-1&&last>-1) {

result=last-first+1;

}

}

return result;

}

posted @ 2015-05-04 09:38  keedor  阅读(...)  评论(...编辑  收藏