Title Descriptioncounts the number of occurrences of a number in a sorted array.
"Thinking" because it is a sorted array, you can use the binary method to search for the value to find in the array of one position, and then to the sides of the scan, encountered unequal to stop.
1 classSolution {2 Public:3 intGetindexbydivision (vector<int> Data,intk) {4 intleft =0, right = Data.size ()-1;5 intMiddle = left + (right-left)/2;6 while(Left <=Right ) {7 if(k >Data[middle])8left = middle +1;9 Else if(K <Data[middle])Tenright = Middle-1; One Else A returnMiddle; -Middle = left + (right-left)/2; - } the return-1; - } - intGETNUMBEROFK (vector<int> Data,intk) { - intindex =getindexbydivision (data,k); + if(Index = =-1)return 0; - intnum =1; + for(inti = index-1; I >=0&& Data[i] = = k;i--) num++; A for(intj = Index +1; J < Data.size () && data[j] = = k;j + +) num++; at returnnum; - } -};
[Sword means offer] 37. Number of occurrences in a sorted array