Returns the number of times a number appears in an ordered array using the binary method.
1. Problem Description
In a given sorted array, find the number of occurrences of the specified number. For example, in the array [1, 2, 3, 4, 4, 4, 4, 6, 8, 9], 4 appears four times.
2. ideas and methods
This problem can be improved on the basis of the binary method. Assume that array a is an incremental series and the number to be searched is num. You can find the starting position and last position of num in array a respectively, calculate the number of times the numeric num appears in array a by the difference between the two.
The c ++ code is as follows:
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Using namespace std; // queries the number of times a specified number appears in an ordered array. isLeft marks the leftmost and rightmost int FindCntofNum (int a [], int len, int num, bool isLeft) {int left = 0, right = len-1; int pos, mid; while (left <= right) // Binary Search {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 rightmost value {left = mid + 1 ;}}} return pos; // return the final position} int main () {int a [10] = {1, 2, 4, 4, 4, 6, 8, 9}; int left, right, dst = 4; left = FindCntofNum (a, 10, 4, true); right = FindCntofNum (a, 10, 4, false); printf ("count of number % d: % d \ n ", dst, right-left + 1); return 0 ;}