Topic:
Counts the number of occurrences of a number in a sorted array.
Ideas:
Refine the binary lookup to find the first occurrence and the last occurrence of the number in the array, so that it appears the number of times.
Take the position of the first occurrence as an example: If the mid element is greater than K, then the first half is searched, if it is less than K, then the second half is searched, and if it is equal to K, then the previous element of the mid is not K, if it is, then this is the position that appears for the initial time.
Time complexity O (logn).
Code:
classSolution { Public: intGETNUMBEROFK (vector<int> Data,intk) {if(Data.size () <=0)return 0;//omg! here too should output 0 intFIRST=GETFIRSTK (Data,k,0, Data.size ()-1); intLAST=GETLASTK (Data,k,0, Data.size ()-1); if(first>=0&& last>=0) { returnlast-first+1; } return 0;//omg!, this is supposed to be 0. }Private: intGETFIRSTK (Constvector<int> &data,intKintBeginintend) { if(begin<0|| End>=data.size () | | Begin>end)return-1; intres=-1; intmid=begin+ (End-begin)/2; if(data[mid]>k) Res=GETFIRSTK (data,k,begin,mid-1); Else if(data[mid]<k) Res=GETFIRSTK (data,k,mid+1, end); Else { if(mid==0|| (mid>0&& data[mid-1]!=k) Res=mid; ElseRes=GETFIRSTK (data,k,begin,mid-1); } returnRes; } intGETLASTK (Constvector<int> &data,intKintBeginintend) { if(begin<0|| End>=data.size () | | Begin>end)return-1; intres=-1; intmid=begin+ (End-begin)/2; if(data[mid]>k) Res=GETLASTK (data,k,begin,mid-1); Else if(data[mid]<k) Res=GETLASTK (data,k,mid+1, end); Else { if(Mid==data.size ()-1|| (Mid<data.size ()-1&& data[mid+1]!=k) Res=mid; ElseRes=GETLASTK (data,k,mid+1, end); } return res;//!!! Forget this sentence, find a good long time error!!! }};
"Sword Point offer" question 38: Number of occurrences of a number in a sorted array