Calculation of number occurrences in an ordered array by dichotomy

Source: Internet
Author: User

1. Description of the problem

Finds the number of occurrences of a specified number in a given array that is already ordered. For example, 4 occurrences in array [1,2,3,4,4,4,4,6,8,9] are 4 times.

2. Ideas and methods

This problem can be improved on the basis of the dichotomy method. Assuming that array A is an ascending sequence, the number that needs to be searched is num, and you can find the starting and last position of Num in array A, respectively, by calculating the number of occurrences of num in array A by the difference between the two.
The C + + code is as follows:

#include <stdio.h>#include <iostream>#include <stdio.h>#include <algorithm>#include <math.h>#include <set>#include <vector>#include <map>using namespace STD;//Find the number of times the specified number appears in an ordered array, isleft marks the leftmost and most rightintFindcntofnum (intA[],intLenintNumBOOLIsleft) {intleft =0, right = Len-1;intPos,mid; while(left <= right)//Two points find{mid = (left + right)/2;if(A[mid] < num) {left = mid +1; }Else if(A[mid] > num) {right = mid-1; }Else{pos = mid;if(Isleft)//Find the leftmost value{right = mid-1; }Else//Find the right value{left = mid +1; }        }    }returnPos//Return to the location of the final find}intMain () {inta[Ten] = {1,2,3,4,4,4,4,6,8,9};intLeft, right, DST =4; left = Findcntofnum (A,Ten,4,true); right = Findcntofnum (A,Ten,4,false);printf("Count of number%d:%d\n", dst,right-left+1);return 0;}

Calculation of number occurrences in an ordered array by dichotomy

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.