题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
轮询
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if (data.empty()) return 0; int cnt = 0; for (int i = 0; i < data.size(); ++i) { if (k == data[i]) { cnt++; } } return cnt; } };
二分
#include <vector> class Solution { public: int GetNumberOfK(vector<int> data ,int k) { if (data.empty()) return 0; int cnt = 0; int left_idx = getLeftRange(data, k); int right_idx = getRightRange(data, k); return right_idx - left_idx + 1; } int getLeftRange(vector<int>& data, int k) { int l = 0; int r = data.size() - 1; while (l <= r) { int mid = l + (r - l) / 2; if (data[mid] >= k) { r = mid - 1; } else if (data[mid] < k) { l = mid + 1; } } return l; } int getRightRange(vector<int>& data, int k) { int l = 0; int r = data.size() - 1; while (l <= r) { int mid = l + (r - l) / 2; if (data[mid] > k) { r = mid - 1; } else if (data[mid] <= k) { l = mid + 1; } } return r; } };
2023-剑指-搜索算法 文章被收录于专栏
2023-剑指-搜索算法