[Sword means offer] 37. Number of occurrences in a sorted array

Source: Internet
Author: User

Title Descriptioncounts the number of occurrences of a number in a sorted array.

"Thinking" because it is a sorted array, you can use the binary method to search for the value to find in the array of one position, and then to the sides of the scan, encountered unequal to stop.

1 classSolution {2  Public:3     intGetindexbydivision (vector<int> Data,intk) {4         intleft =0, right = Data.size ()-1;5         intMiddle = left + (right-left)/2;6          while(Left <=Right ) {7             if(k >Data[middle])8left = middle +1;9             Else if(K <Data[middle])Tenright = Middle-1; One             Else  A                 returnMiddle; -Middle = left + (right-left)/2; -         } the         return-1; -     } -     intGETNUMBEROFK (vector<int> Data,intk) { -         intindex =getindexbydivision (data,k); +         if(Index = =-1)return 0; -         intnum =1; +          for(inti = index-1; I >=0&& Data[i] = = k;i--) num++; A          for(intj = Index +1; J < Data.size () && data[j] = = k;j + +) num++; at         returnnum; -     } -};

[Sword means offer] 37. 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.