题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
//左边界 和 右边界
int lbound = 0,rbound = 0;
int l = 0,r = data.size();
// 二分法找左边界,要求左边的值小于k,右边的值>=k
while(l<r){
int mid = (l+r)/2;
if(data[mid] < k) l = mid+1;
else r = mid;
//找左边界 如果mid小于k说明可以mid+1 mid必不为k
}
lbound = l;
l = 0,r = data.size();
while(l<r){
int mid = (l+r)/2;
if(data[mid]<=k) l = mid+1;
else r = mid;
}
rbound = l;
return rbound - lbound;
}
};
二分很容易想到 就是具体的界限最好手动算一下