Topic
Counts the number of occurrences of a number in a sorted array.
Solving
Method One: Violence
Linear traversal
Method 2:2 Division Method
To find out the left and right boundary respectively
Public classSolution { Public intGETNUMBEROFK (int[]Array,intK) {if(Array= = Null| |Array. length==0)return 0;intLow =0;intHigh =Array. Length-1;intL = Left (Array, low,high,k);if(L ==-1)return 0;intR = Right (Array, l,high,k);returnR-l +1; }//Seek left Border Public intLeftint[]Array,intLow,intHighintK) {if(Array[Low] = = k)returnLow while(Low <= High) {intMID = low + (high-low)/2;if(Mid >=1&&Array[mid-1]!=k &&Array[Mid] ==k)//mid-1 cross-border to judge returnMidif(Array[mid] >=k) {//Consider equalsHigh = mid-1; }Else{Low = mid +1; } }return-1; }//Seek right border Public intRightint[]Array,intLow,intHighintK) {if(Array[high] = = k)returnHigh while(Low <= High) {intMID = low + (high-low)/2;if(Mid +1<Array. length &&Array[Mid]==k &&Array[mid+1]!=k)//Mid + 1 out of bounds to judge returnMidif(Array[mid] >k) {high = mid-1; }Else{//equals to be considered hereLow = mid +1; } }return-1; }}
Of course, you can also find a boundary and then line it up.
Number of occurrences of the number in the sorted array