Number of occurrences of the number in the sorted array
- Number of participants: 1216 time limit: 1 seconds space limit: 32768K
- By scale: 28.43%
- Best record: 0 ms|0k(from)
The topic description counts the number of occurrences of a number in a sorted array.
Test instructions: First the array is an ordered increment sequence already arranged! To count the occurrences of a number, which is equivalent to inserting a number in an ordered sequence, then I just need to determine the position of the insertion, using the idea of a fast line, or a dichotomy, if K is found in the array, then the left and right expansion boundary can be determined by the number of occurrences in the array.
Some special cases can be specially sentenced! For example, K is less than the minimum number of arrays, or greater than the maximum number;
Class Solution {public: int GETNUMBEROFK (vector<int> data, int k) { if (data.size () <=0) return 0; if (data[0]>k | | data[data.size () -1]<k) return 0; int left=0; int Right=data.size ()-1; int x=0,y=0,len=right; BOOL Bo=false; while (Left<=right) { int mid= (left+right)/2; if (data[mid]==k) { bo=true; X=y=mid; while (Y+1<=len && data[y+1]==k) ++y; while (x-1>=0 && data[x-1]==k)--x; break; } if (data[mid]>k) { right=mid-1; } else if (data[mid]<k) { left=mid+1; } } printf ("x=%d\ty=%d\n", X, y); if (bo) return y-x+1; else return 0; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Number of occurrences of numbers in a sorted array (point of offer) take advantage of the idea of quick-line (O (LOGN))