"Sword Point offer" question 38: Number of occurrences of a number in a sorted array

Source: Internet
Author: User

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

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.