采用二分查找的方法,一旦找到,left++,right--,--middle++,扩展查找。
开始while(left<right),当n=1时不能进入循环,应写while(left<=right)
1 class Solution { 2 public: 3 int GetNumberOfK(vector<int> data ,int k) { 4 int n=data.size(); 5 if(n<1) return 0; 6 int left=0; 7 int right=n-1; 8 int middle=0; 9 int count=0; 10 while(left<=right){ 11 if(data[left]==k){ 12 while(data[left]==k&&left<n){ 13 left++; 14 count++; 15 } 16 return count; 17 } 18 if(data[right]==k){ 19 while(data[right]==k&&right>=0){ 20 right--; 21 count++; 22 } 23 return count; 24 } 25 middle=left+(right-left)/2; 26 if(data[middle]==k){ 27 count++; 28 int m=middle-1; 29 while(data[m]==k&&m>=0){ 30 m--; 31 count++; 32 } 33 m=middle+1; 34 while(data[m]==k&&m<n){ 35 m++; 36 count++; 37 } 38 return count; 39 } 40 if(data[middle]>k) 41 right=middle-1; 42 else 43 left=middle+1; 44 } 45 return count; 46 } 47 };