upper_bound用法: upper_bound(first,last,val); 用来查找序列中第一个大于指定目标值的元素.
lower_bound用法: upper_bound(first,last,val); 用来查找序列中第一个不小于目标值的元素
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int l = 0, r = data.size();
while(l < r){
int m = l + (r - l)/2;
if(data[m] < k){
l = m + 1;
}else{
r = m;
}
}
int low_bound = l;
l = 0, r = data.size();
while(l < r){
int m = l + (r - l)/2;
if(data[m] <= k){
l = m + 1;
}else{
r = m;
}
}
int upp_bound = l;
return upp_bound - low_bound;
}
};
函数调用:
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
return upper_bound(data.begin(),data.end(),k)-lower_bound(data.begin(),data.end(),k);
}
};
|