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