Title: Counts the number of occurrences of a number in a sorted array. For example, input sort array {1,2,3,3,3,3,4,5}, because 3 appears in this array 4 times, so output 4.
Analysis: Direct method, sequential scan array Gets the number of occurrences. The time complexity is O (n). Faster method, because the array is orderly, you can use the dichotomy to get the first 3 and the last 3 position, it is determined how many times. Time Complexity of O (LOGN)
Realize:
INT&NBSP;GETFIRSTK (int* data,int length,int k,int start,int end) // Get the position of the first K { if (start>end) return -1; int middleindex= (Start+end)/2; int middleData=data[middleIndex]; if (middledata==k) { if (middleIndex>0 &&DATA[MIDDLEINDEX-1]!=K) | | middleindex==0) return middleindex ; else end=middleindex-1; } else if (MiddleData >K) end=middleindex-1; else start=middleindex+1; &NBSP;&NBSP;RETURN&NBSP;GETFIRSTK (data,length,k,start,end);} INT&NBSP;GETLASTK (int* data,int length,int k,int start,int end) // Get the last k position { if (start>end) return -1; int middleindex= (start+ End)/2; int middledata=data[middleindex]; if (Middledata==k) { if (( MIDDLEINDEX<LENGTH-10&&DATA[MIDDLEINDEX+1]!=K) | | MIDDLEINDEX==LENGTH-1) return middleindex; else start=middleindex+1; } else if (middleData<k) start=middleIndex+1; else end=middleindex-1; return getlastk (data,length,k,start,end);} INT&NBSP;GETNUMBEROFK (int* data,int length,int k) { int number=0; if (data!=null&&length>0) { &NBSP;&NBSP;&NBSP;&NBSP;INT&NBSP;FIRST=GETFIRSTK (data,length,k,0,length-1); &NBSP;&NBSP;&NBSP;INT&NBSP;LAST=GETLASTK (data,length,k,0,length-1); if (first>-1&&last>-1) number=last-first+1; } &nbSp; return number;}
This article from "Fairy Road thousands of dust Dream" blog, please be sure to keep this source http://secondscript.blog.51cto.com/9370042/1587763
Number of occurrences of the number in the sorted array