Number of number k occurrences in sorted array

Source: Internet
Author: User

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

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.