题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if (data.size() == 0) return 0;
int l = 0, r = data.size() - 1, mid = 0;
int left = 0, right = 0;
while (l < r) {
mid = l + r >> 1;
if (data[mid] < k) {
l = mid + 1;
} else {
r = mid;
}
}
if (data[l] != k) return 0;
left = l;
l = 0, r = data.size() - 1;
while (l < r) {
mid = l + r + 1 >> 1;
if (data[mid] <= k) {
l = mid;
} else {
r = mid - 1;
}
}
return l - left + 1;
}
};