1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: int bin_search(const vector<int> &data, const int k) { int left = 0, right = data.size(); while (left < right) { const int mid = (left + right) / 2; if (data[mid] > k) { right = mid; } else if (data[mid] == k) { right = mid; } else { left = mid + 1; } } return left; } int GetNumberOfK(vector<int> data ,int k) { int left = bin_search(data, k); int right = bin_search(data, k + 1); return right - left; } };
|