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