"title" counts the number of occurrences of a number in a sorted array.
1 PackageCom.exe9.offer;2 3 /**4 * "title" counts the number of occurrences of a number in a sorted array. 5 * @authorWGS6 *7 */8 Public classGETNUMOFK {9 Public intGETNUMOFK (int[] arr,inttarget) {Ten if(arr==NULL|| arr.length<=0)return-1; One intlen=arr.length; A intCount=0; - - the intLASTINDEX=FINDLASTK (arr, target, 0, len-1); -System.out.println ("= = =" +lastIndex); - if(Lastindex==-1) - return-1; + intFIRSTINDEX=FINDFIRSTK (arr, target, 0, len-1); -System.out.println ("= = =" +firstindex); + A if(Firstindex>=0 && lastindex>=0) atCount=lastindex-firstindex+1; - - returncount; - - } - in //first, look for the duplicate numbers out of the left position. - Public intFINDFIRSTK (int[] arr,intTargetintStartintend) { to if(Start>end)return-1; + - intmidindex= (start+end)/2; the intMidval=Arr[midindex]; * $ if(midval==target) {Panax Notoginseng while(midval==target) { -midindex--; theMidval=Arr[midindex]; + } A returnMidindex+1; the}Else if(midval<target) { +Start=midindex+1; -}Else{//Midval>target $End=midindex-1; $ } - - returnFindfirstk (arr,target,start,end); the - }Wuyi ////first, look for the duplicate numbers out of the right position. the Public intFINDLASTK (int[] arr,intTargetintStartintend) { - if(Start>end)return-1; Wu intmidindex= (start+end)/2; - intMidval=Arr[midindex]; About $ if(midval==target) { - while(midval==target) { -midindex++; -Midval=Arr[midindex]; A } + returnMidIndex-1; the}Else if(midval<target) { -Start=midindex+1; $}Else{//Midval>target theEnd=midindex-1; the } the the returnFindfirstk (arr,target,start,end); - in } the the Public Static voidMain (string[] args) { About int[] arr=New int[]{1}; theGETNUMOFK g=NewGETNUMOFK (); the intNUM=G.GETNUMOFK (arr, 3); the System.out.println (num); + - } the Bayi}
The sword refers to the offer series---number of occurrences in the array