"Sword Point offer" topic 38 number of occurrences in a sorted array

Source: Internet
Author: User

Ideas:

Should be used to find the first and last occurrence of the number of two points, subtract. O (LOGN)

intFindleft (intA[],intNintnum) {    intL =0, R = N-1;  while(L <=r) {intm = L + (r-l)/2; if(a[m] = = num)//The difference between the common binary search equals here        {            if(M = =0|| A[m-1]! = num)//If this is the first number or the number in front of it is not Num then this position is where the first num appears.                returnm; Else   //otherwise num in the left halfr = M-1; }        Else if(A[m] <num) {L= m +1; }        Else{R= M-1; }    }    return-1;//didn't find}intFindright (intA[],intNintnum) {    intL =0, R = N-1;  while(L <=r) {intm = L + (r-l)/2; if(A[m] = =num) {            if(M = = N-1|| A[m +1]! = num)////If this is the last number or the number behind it is not Num then this position is where the last num appears.                returnm; Else //otherwise the last num in the right halfL = m +1; }        Else if(A[m] <num) {L= m +1; }        Else{R= M-1; }    }    return-1;//didn't find}intTimesintA[],intNintnum) {    if(A = = NULL)return 0; intL =Findleft (A, n, num); intR =Findright (A, n, num); return(L = =-1|| r = =-1) ?0: R-l +1;}intMain () {inta[Ten] = {1,2,3,3,3,3,4,5}; intAns = times (A,8,5); return 0;}

The first thing to write is to use normal binary search to find a specified number and then expand Around, O (N) is not good.

//O (N) solution is not goodintAppeartimes (intA[],intNintnum) {    intL =0; intr = N-1; intpos =-1;//The subscript for the found Num     while(L <= R)//Two-point lookup to find a num    {        intm = L + (r-l)/2; if(A[m] = =num) {POS=m;  Break; }        Else if(A[m] <num) L= m +1; ElseR= M-1; }    if(pos = =-1)//no such number        return 0; L= R =POS;  while(L >=0&& a[l] = = num)//find the left borderl--;  while(R < n && a[r] = = num)//find the right borderr++; returnR-l-1;}

"Sword Point offer" topic 38 number of occurrences 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.