剑指offer 66题 -- 数字在排序数组中出现的次
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.size() <=0)
return 0;
int result = 0;
int index = -1;
index = binSearch(data, 0, data.size()-1, k);
if(index == -1)
return 0;
int val = data[index];
int left=index, right=index;
while(data[left] == val && left>=0)
left--;
while(data[right] == val && right <=data.size()-1)
right++;
result = right-left -1;
return result;
}
// 递归式二分查找
int binSearch(vector<int> data, int low, int high, int key)
{
int mid = (high+low)/2;
if(low <= high)
{
if(key == data[mid])
return mid;
else if(key < data[mid])
return binSearch(data, low, mid-1, key);
else
return binSearch(data, mid+1, high, key);
}
else
return -1;
}
/* 非递归式二分查找
int binSearch(vector<int> data, int low, int high, int key)
{
int head = low;
int tail = high;
int mid=0;
while(head <= tail)
{
mid = (head+tail)/2;
if(key == data[mid])
return mid;
else if(key < data[mid])
tail = mid-1;
else if(key > data[mid])
head = mid +1;
}
return -1;
}
};