Number of occurrences of the number in the sorted array

Source: Internet
Author: User

The topic description counts the number of occurrences of a number in a sorted array. Idea: Sort array is sorted array, for the order of the array, we will think of the dichotomy, the subject is the binary method to find the value, then return the subscript, and then on the left and right side of the count to find. Code:
intBinarySearch (vector<int> Data,intLowintHighintk) { while(Low <=High ) {            intm = low + (high-low)/2; if(Data[m] = =k)returnm; Else if(Data[m] >k) high= M1; Else Low= m+1; }        return-1; }    intGETNUMBEROFK (vector<int> Data,intk) {intLen =data.size (); intindex; Index= BinarySearch (data,0, len-1, K); if(Index = =-1)            return 0; intLow = index-1; intN1 =0; intN2 =0; intHigh = index+1;  while(Low >=0) && (Data[low] = =k)) { Low--; N1++; }         while((High<len) && (Data[high] = =k)) { high++; N2++; }        returnn1+n2+1; }

See the special idea:

Idea: For example: Sample 1,2,4,4,5,6 Find the number of 4, then 3.5 and 4.5 are inserted, 1, 2, 3.5, 4, 4, 4.5, 5, 6 is 4.5 of the position minus 3.5 is the number of 4.

However, this method is less complex than the time of the previous method when the element is small. Because you want to invoke the two-time dichotomy.

    intGETNUMBEROFK (vector<int> Data,intk) {returnBisearch (data, K +0.5)-Bisearch (data, K-0.5) ; }    intBisearch (Constvector<int> & Data,Doublenum) {        ints =0, E = Data.size ()-1;  while(S <=e) {            intMid = (e-s)/2+s; if(Data[mid] <num) s= Mid +1; Else if(Data[mid] >num) e= Mid-1; }        returns; }

Comparison of two methods:

The complexity is similar, but the first method is more complex, the best complexity is lower, and not stable enough. The two points are more stable, but less efficient than the first.

Number of occurrences of the number in the 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.