Title Description
Count the number of occurrences of a number in a sorted array
Idea 1: The cycle of Violence O (N)
public class Solution {
public int GETNUMBEROFK (int [] A, int k) {
int cnt=0;
for (int i=0;i<a.length;i++)
if (a[i]==k)
cnt++;
return CNT;
}
}
Idea 2: Using two points to find O (LOGN)
Use the binary search to find the first occurrence of the number of the position and the last occurrence of the position.
2 position difference is the number of times.
Use 2 to find the first K (the number to be asked), take K compared to the middle of the array, if K is large, then go to the second half to find;
If k is small, then go to the first half to find, if equal, to determine whether the current K is not the first time to appear. (if k is equal to the number in front of K, it is not the first occurrence, if K is greater than the number before the K, it is the first occurrence), if K is not the first time, then go to K before continuing to find, if it is the first occurrence, then found the position.
1 Public classSolution {2 Public intGETNUMBEROFK (int[] A,intk) {3 if(a.length==0)return0;4 intf =Getfirstk (A, k);5 intL =Getlstk (a,k);6 if(A[f]==k && a[l]==k)7 returnL-f+1;8 Else9 return0;Ten } One A Private intGETFIRSTK (intA[],intk) { - - intLo = 0,hi=a.length-1; the intMid =0; - while(true) { - if(Lo>=hi)returnHi; -Mid = (Hi-lo)/2+Lo; + if(k<A[mid]) -Hi=mid-1; + Else if(k>A[mid]) { ALo=mid+1; at } - Else { - if(mid-1>=lo&&a[mid-1]==k) -hi = mid-1; - Else - returnmid; in } - } to } + Private intGETLSTK (intA[],intk) { - the intLo = 0,hi=a.length-1; * intMID = 0; $ while(true) {Panax Notoginseng if(Lo>=hi)returnLo; -Mid = (Hi-lo)/2+Lo; the if(k<A[mid]) +Hi=mid-1; A Else if(k>A[mid]) { theLo=mid+1; + } - Else { $ if(mid+1<=hi&&a[mid+1]==k) $Lo = mid+1; - Else - returnmid; the } - } Wuyi } the - Wu -}
Number of occurrences of the 37 number in the sorted array