classSolution{public:intGetNumberOfK(vector<int> data ,int k){if(data.size()==0)return0;int left =getFirstk(data,0, data.size()-1, k);int right =getLastk(data,0, data.size()-1, k);if(left !=-1&& right !=-1){return right - left +1;}return0;}private:intgetFirstk(vector<int> data,int l,int r,int k){if(l > r)return-1;//不能带等号int m = l +(r - l)/2;int midValue = data[m];if(midValue == k){if(m >0&& data[m -1]!= k || m ==0){return m;}else
r = m -1;}elseif(midValue < k)
l = m +1;else
r = m -1;returngetFirstk(data, l, r, k);}intgetLastk(vector<int> data,int l,int r,int k){if(l > r)return-1;//不能带等号int m = l +(r - l)/2;int midValue = data[m];if(midValue == k){if(m < data.size()-1&& data[m +1]!= k || m == data.size()-1){return m;}else{
l = m +1;}}elseif(midValue < k)
l = m +1;else
r = m -1;returngetLastk(data, l, r, k);}};