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