剑指offer:统计一个数字在排序数组中出现的次数。
思路:改进二分查找算法,找到第一个K出现的索引,和第最后一个k的索引。
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
//必须先考虑边境条件
int vecLen = data.size();
if(vecLen == 0)
return 0;
//GetFirstKIndex,改良二分查找法,找到最左边K的索引
int leftIndexOfK = GetFirstKIndex(data,k,vecLen);
if(leftIndexOfK == -1)//如果不存在k,返回零。
return 0;
int RightIndexOfK = GetLastKIndex(data,k,vecLen);
return RightIndexOfK - leftIndexOfK + 1;
}
int GetFirstKIndex(vector<int> &data, int k, int length ){
int low,high,mid;
low = 0;
high = length - 1;
while(low <= high){
mid = (low + high) / 2;
if(data[mid] > k)
high = mid -1;
else if(data[mid] < k)
low = mid + 1;
else if(data[mid] == k){
if(mid > 0 && data[mid - 1] != k)
return mid;
else if(mid == 0)
return mid;
else high = mid -1;
}
}
return -1;
}
int GetLastKIndex(vector<int> &data, int k, int length ){
int low,high,mid;
low = 0;
high = length - 1;
while(low <= high){
mid = (low + high) / 2;
if(data[mid] > k)
high = mid -1;
else if(data[mid] < k)
low = mid + 1;
else if(data[mid] == k){
if(mid < length && data[mid + 1] != k)
return mid;
else if(mid == length)
return mid;
else low = mid +1;
}
}
return -1;
}
};