The number of occurrences in a sorted array of "sword point 38"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.