The topic description counts the number of occurrences of a number in a sorted array. Idea: Sort array is sorted array, for the order of the array, we will think of the dichotomy, the subject is the binary method to find the value, then return the subscript, and then on the left and right side of the count to find. Code:
intBinarySearch (vector<int> Data,intLowintHighintk) { while(Low <=High ) { intm = low + (high-low)/2; if(Data[m] = =k)returnm; Else if(Data[m] >k) high= M1; Else Low= m+1; } return-1; } intGETNUMBEROFK (vector<int> Data,intk) {intLen =data.size (); intindex; Index= BinarySearch (data,0, len-1, K); if(Index = =-1) return 0; intLow = index-1; intN1 =0; intN2 =0; intHigh = index+1; while(Low >=0) && (Data[low] = =k)) { Low--; N1++; } while((High<len) && (Data[high] = =k)) { high++; N2++; } returnn1+n2+1; }
See the special idea:
Idea: For example: Sample 1,2,4,4,5,6 Find the number of 4, then 3.5 and 4.5 are inserted, 1, 2, 3.5, 4, 4, 4.5, 5, 6 is 4.5 of the position minus 3.5 is the number of 4.
However, this method is less complex than the time of the previous method when the element is small. Because you want to invoke the two-time dichotomy.
intGETNUMBEROFK (vector<int> Data,intk) {returnBisearch (data, K +0.5)-Bisearch (data, K-0.5) ; } intBisearch (Constvector<int> & Data,Doublenum) { ints =0, E = Data.size ()-1; while(S <=e) { intMid = (e-s)/2+s; if(Data[mid] <num) s= Mid +1; Else if(Data[mid] >num) e= Mid-1; } returns; }
Comparison of two methods:
The complexity is similar, but the first method is more complex, the best complexity is lower, and not stable enough. The two points are more stable, but less efficient than the first.
Number of occurrences of the number in the sorted array