Ideas:
Using the binary search, we find the index of the head and tail of the statistic, and the result is the difference of the last one.
C++:
1#include <iostream>2#include <vector>3 using namespacestd;4 5 intGETFIRSTK (vector<int>& Nums,intStartpos,intEndpos,intk)6 {7 if(Startpos >endpos)8 return-1;9 Ten intMid = (startpos + endpos)/2; One A if(Nums[mid] = =k) - { - if(Mid = =0|| (Mid >0&& Nums[mid-1] !=k)) the returnmid; - Else -Endpos = mid-1; - } + Else if(Nums[mid] <k) - { +Startpos = mid +1; A } at Else - { -Endpos = mid-1; - } - - returnGetfirstk (Nums, Startpos, Endpos, k); in } - to intGETLASTK (vector<int>& Nums,intStartpos,intEndpos,intk) + { - if(Startpos >endpos) the return-1; * $ intMid = (startpos + endpos)/2;Panax Notoginseng intLastpos = Nums.size ()-1; - the if(Nums[mid] = =k) + { A if(Mid = = Lastpos | | (Mid < Lastpos && Nums[mid +1] !=k)) the returnmid; + Else -Startpos = mid +1; $ } $ Else if(Nums[mid] <k) - { -Startpos = mid +1; the } - ElseWuyi { theEndpos = mid-1; - } Wu - returnGetlastk (Nums, Startpos, Endpos, k); About } $ - intMain () - { - inta[Ten] = {1,2,3,3,3,3,3,4,4,5}; Avector<int> V (A, A +Ten); + theCout<<getlastk (V,0,9,4)-Getfirstk (V,0,9,4) +1<<Endl; -}
The number of occurrences in a sorted array of "sword point 38"