Title: Counts the number of occurrences of a number in a sorted array. For example, enter the sorted array {1,2,3,3,3,3,4,5} and the number 3, because 3 appears in this array 4 times, so output 4.
Idea 1: The solution is the most intuitive solution, you can first use the binary search to find this element, and then go to the left and right, the same number of elements are calculated.
Idea 2: Using the extension of the binary lookup, when the found element has duplicates, find the first and last of the elements, so that you can calculate how many duplicates of the element.
1#include <stdio.h>2#include"stdafx.h"3 4 intGETFIRSTK (int* Data,intLengthintKintStartintend);5 intGETLASTK (int* Data,intLengthintKintStartintend);6 7 intGETNUMBEROFK (int* Data,intLengthintk)8 {9 intNumber =0;Ten One if(Data! = NULL && length >0) A { - intFirst = GETFIRSTK (data, length, K,0, Length-1); - intLast = GETLASTK (data, length, K,0, Length-1); the - if(First >-1&& Last >-1) -Number = Last-first +1; - } + - returnNumber ; + } A at intGETFIRSTK (int* Data,intLengthintKintStartintend) - { - if(Start >end) - return-1; - - intMiddleindex = (start + end)/2; in intMiddledata =Data[middleindex]; - to if(Middledata = =k) + { - if((Middleindex >0&& Data[middleindex-1]! = k) | | Middleindex = =0) the returnMiddleindex; * Else $End = Middleindex-1;Panax Notoginseng } - Else if(Middledata >k) theEnd = Middleindex-1; + Else AStart = Middleindex +1; the + returnGETFIRSTK (data, length, K, start, end); - $ } $ - intGETLASTK (int* Data,intLengthintKintStartintend) - { the if(Start >end) - return-1;Wuyi the intMiddleindex = (start + end)/2 ; - intMiddledata =Data[middleindex]; Wu - if(Middledata = =k) About { $ if((Middleindex < length-1&& Data[middleindex +1]! = k) | | Middleindex = = Length-1) - returnMiddleindex; - Else -Start = Middleindex +1; A } + Else if(Middledata <k) theStart = Middleindex +1; - Else $End = Middleindex-1; the the returnGETLASTK (data, length, K, start, end); the } the - intMain () in { the intData[] = {1,2,3,3,3,3,4,5}; the intLength =sizeof(data)/sizeof(int); About intK =3; the for(inti =0; i < length; ++i) theprintf"%d\t", Data[i]); theprintf"\ n"); + intresult =GETNUMBEROFK (data, length, k); -printf"%d occurrences%d times \ n", K,result); the Bayi return 0; the}
Number of occurrences of the number in the sorted array