题目描述
统计一个数字在排序数组中出现的次数。
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int n = data.size();
int start = 0;
int end = n-1;
int mid;
int count = 0;
while(start<=end)
{
mid = (start + end)>>1;
if(data[mid] == k)
break;
else if(data[mid] < k)
start = mid + 1;
else
end = mid - 1;
}
if(start>end)
return 0;
int index1 = mid;
while(index1>=0&&data[index1]==k)
{
count ++;
index1 --;
}
int index2 = mid + 1;
while(index2<n&&data[index2]==k)
{
count ++;
index2 ++;
}
return count;
}
};