Idea: If you traverse an array from start to finish, the time complexity is O (n). We can take advantage of the conditions given by the topic, because it is a sorted array , we can use binary lookup to achieve the time complexity O (log2N)
The specific code is as follows:
#include <iostream> #include <cassert>using namespace std;int findfirstk (int *ar, int len, int k, int start, int END)//Use the binary search to find the position where the first k appears {if (Start > End) {return-1;} int mid = (End-start)/2 +start;if (ar[mid] = = k) {if (Mid>0&&ar[mid-1]!=k | | mid==0)//Find First k{return mid;} Else{end = Mid-1;}} else if (Ar[mid] > k) {end = Mid-1;} Else{start = mid + 1;} Return Findfirstk (AR, Len, K, start, end);} int findlastk (int *ar, int len, int k, int start, int end)//Use binary lookup to find the last position where K appears {if (Start > End) {return-1;} int mid = (End-start)/2 +start;if (ar[mid] = = k) {if (Mid<len-1&&ar[mid+1]!=k | | mid==len-1)//Find last K{return Mid;} Else{start = mid + 1;}} else if (Ar[mid] > k) {end = Mid-1;} Else{start = mid + 1;} Return Findlastk (AR, Len, K, start, end);} int gettimesk (int *ar, int len, int k) {assert (ar! = NULL); int times = 0;int first = FINDFIRSTK (AR, Len, K, 0, len-1); int L AST = FINDLASTK (AR, Len, K, 0, len-1); if (first>-1 && last>-1 && len>0) {times = Last-first+1;} return times;} int main () {int ar[] = {1,2,3,4,4,5,6,6,6,6,6,7,7,7,7,8,8,9,9,9,9,9,10};int len = sizeof (AR)/sizeof (ar[0]); int k;cin >>k;cout<< "digital" <<k<< "<<gettimesk" (AR, Len, k) << "Times" <<endl;return 0;
Number of number k occurrences in sorted array