题目描述
统计一个数字在排序数组中出现的次数。
一:使用二分查找确定k的第一次出现位置和最后一次出现位置
时间复杂度O(nlogn)
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int lower = getLower(data,k);
int upper = getUpper(data,k);
return upper - lower + 1;
}
//获取k第一次出现的下标
int getLower(vector<int> data,int k){
int start = 0,end = data.size()-1;
int mid = (start + end)/2;
while(start <= end){
if(data[mid] < k)
start = mid + 1;
else
end = mid - 1;
mid = (start + end)/2;
}
return start;
}
//获取k最后一次出现的下标
int getUpper(vector<int> data,int k){
int start = 0,end = data.size()-1;
int mid = (start + end)/2;
while(start <= end){
if(data[mid] <= k)
start = mid + 1;
else
end = mid - 1;
mid = (start + end)/2;
}
return end;
}
};
//数组中均为整数,可以将搜索两个k的位置修改为,搜索k-0.5和k+0.5,
//可缩减代码量,时间复杂度仍然为O(nlogn)
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
return biSearch(data, k+0.5) - biSearch(data, k-0.5) ;
}
private:
int biSearch(const vector<int> & data, double num){
int s = 0, e = data.size()-1;
while(s <= e){
int mid = (e - s)/2 + s;
if(data[mid] < num)
s = mid + 1;
else if(data[mid] > num)
e = mid - 1;
}
return s;
}
};