Topic:
In the sorted array, find out the number of occurrences of a given number
Ideas:
Since there is a sort array, it is easy to think of binary lookups, with time complexity O (LOGN);
First, by binary find the leftmost occurrence of the number of the subscript left (if not found, then return-1), and then through the binary search find the rightmost occurrence of the number of the following table right (if not found, then return-1), and then right-left+1 is the number of occurrences;
Code:
#include <iostream>using namespace Std;int binarysearchcount (int *array,int len,int data) {if (len<1) return-1 ; int left=0; int right=len-1; int mid; int leftindex=-1; Find the left index while (left<=right) {mid=left+ ((right-left) >>1); if (array[mid]==data) {leftindex=mid; Right=mid-1; } else if (array[mid]<data) left=mid+1; else right=mid-1; }//Find the right index left=0; right=len-1; int rightindex=-1; while (left<=right) {mid=left+ ((right-left) >>1); if (array[mid]==data) {rightindex=mid; left=mid+1; } else if (array[mid]<data) left=mid+1; else right=mid-1; } if (Leftindex!=-1 && rightindex!=-1) return rightindex-leftindex+1; else return 0;} int main () {int arr[]={0,1,2,3,3,3,3,3,3,3,4,5,6,7,13,19}; int len=sizeof (arr)/sizEOF (Arr[0]); cout << Binarysearchcount (arr,len,18) << Endl; return 0;}
(algorithm: Binary lookup) in a sorted array, to find out the number of occurrences of a given number