# 两次二分查找

``````#include <vector>
#include <iostream>
using namespace std;

class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
if(data.empty())
return 0;

int firstPos = GetFirstPos(data, k, 0, data.size() - 1);
int lastPos = GetLastPos(data, k, 0, data.size() - 1);
if((firstPos == -1) || (lastPos == -1))
return 0;
else
return lastPos - firstPos + 1;
}

int GetFirstPos(vector<int>& data, int k, int left, int right){
if(left > right)
return -1;

int ret;
int center = (left + right) >> 1;

if(data[center] < k){
ret = GetFirstPos(data, k, center + 1, right);
}
else if(data[center] > k){
ret = GetFirstPos(data, k, left, center - 1);
}
else{
if(center == 0)
return 0;

if(data[center - 1] != k)
return center;
else
ret = GetFirstPos(data, k, left, center - 1);
}
return ret;
}

int GetLastPos(vector<int>& data, int k, int left, int right){
int center = (left + right) >> 1;

while(left <= right){
if(data[center] < k)
{
left = center + 1;
}
else if(data[center] > k)
{
right = center - 1;
}
else
{
if((center + 1) < static_cast<int>(data.size()) && data[center + 1] == k)
left = center + 1;
else
return center;
}
center = (left + right) >> 1;
}
return -1;
}
};

int main()
{
Solution obj;
vector<int> input = {3, 3, 3, 3, 4, 5};
int ret = obj.GetNumberOfK(input, 3);
cout << ret << endl;
return 0;
}``````