public static int getFirst(int[] data,int start,int end,int key) { if(data == null)return -2; if(start > end ) return -1; int mid = ( start+end )/2; int midData = data[mid]; if(midData == key) { if(( mid >0 && data[mid-1] !=key)|| mid==0) return mid; else return getFirst(data, start, mid-1, key);//可以修改让其只返回一个return }else if(midData > key) return getFirst(data, start, mid-1, key); else return getFirst(data, mid+1, end, key); } public static int getLast(int[] data,int start,int end,int key) { if(data == null)return -2; if(start > end)return -1; int mid = (start+end)/2; int midData = data[mid]; if(midData == key) { if(( mid < data.length-1 && data[mid+1] !=key )|| mid == data.length-1 ) return mid; else return getLast(data, mid+1, end, key); } else if(midData > key) return getLast(data, start, mid-1, key); else return getLast(data, mid+1, end, key); } public static void getNumber(int[] data,int key) { int startIndex = getFirst(data, 0, data.length-1,key); int endIndex = getLast(data, 0, data.length-1,key); if(startIndex >-1 && endIndex > -1) System.out.println(endIndex-startIndex+1); else System.out.println("no"); }
版权声明:本文为博主原创文章,转载请注明出处。
原文地址:http://blog.csdn.net/u014307117/article/details/47791703