题目描述
统计一个数字在排序数组中出现的次数。
1 class Solution { 2 public: 3 int GetNumberOfK(vector<int> data ,int k) { 4 int len= data.size(); 5 if (len == 0) 6 return 0; 7 bool find = 0; 8 int begin = 0,end = len -1,mid; 9 while(begin <= end) 10 { 11 mid = (begin + end)/2; 12 if(data[mid] > k) 13 { 14 end = mid - 1; 15 } 16 else if(data[mid] < k) 17 { 18 begin = mid + 1; 19 } 20 else 21 { 22 find = 1; 23 break; 24 } 25 } 26 if(!find) 27 return 0; 28 29 int cnt = 1; 30 int i = mid + 1; 31 while(i < len && data[i] == k) 32 { 33 ++ cnt; 34 ++i; 35 } 36 i = mid - 1; 37 while(i >=0 && data[i] == k) 38 { 39 ++ cnt; 40 --i; 41 } 42 return cnt; 43 } 44 };