Title: Counts the number of occurrences of a number in a sorted array.
Idea: Using a binary lookup, find the position where the number first appears in the array, and then find the one that appears after the group. The two do subtraction and add 1.
Java code:
//Number of occurrences of the numeric k in the sorted array//idea: Find the first k and the last K with two points Public classNumbercount { Public intNumbercount (int[] A,intk) { if(a==NULL) return0; intStart=0; intEnd=a.length-1; intfirst=Firstk (a,k,start,end); intlast=ENDK (a,k,start,end); returnLast-first+1; } //find the last k by two-point search Private intENDK (int[] A,intKintStartintend) { if(a==NULL) return0; intMiddle= (start+end)/2; if(a[middle]==k) { if(a[middle]==k&&a[middle+1]!=k| | Middle==a.length-1) returnMiddle; ElseStart=middle+1; } Else if(a[middle]<k) Start=middle+1; ElseEnd=middle-1; returnENDK (a,k,start,end); } //find the first k with a binary search Public intFIRSTK (int[] A,intKintStartintend) { if(a==NULL) return0; intMiddle= (start+end)/2; if(a[middle]==k) { if(middle==0| | a[middle-1]!=k&&a[middle]==k)returnMiddle; ElseEnd=middle-1; } Else if(a[middle]<k) Start=middle+1; ElseEnd=middle-1; returnFirstk (a,k,start,end); } Public Static voidMain (string[] args) {int[] a={1,3,3,3,7,4,5}; Numbercount Numbercount=NewNumbercount (); intNumber=numbercount.numbercount (A, 3); SYSTEM.OUT.PRINTLN (number); }}
The sword refers to the offer-in the sixth chapter of the interview (number of occurrences in the sorted array)