class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
return origMethod(data, k);
}
/*方法一: 哈希表*/
int hashMethod(vector<int> data,int k){
unordered_map<int,int> result;
for(int val:data){
if(val == k){
++result[val];
}
}
return result[k];
}
/*方法二: 二分查找*/
/*找最左边索引*/
int bisserch(vector<int>data, int k,int left,int right){
if(left > right || data[left] > k || data[right] < k){
return -1;
}else{
int mid = (left+right)/2;
if(data[left] == k){
return left;
} int dp = bisserch(data,k, left, mid);
if(dp != -1){
return dp;
}
return bisserch(data, k, mid+1, right);
}
}/*找最右边索引*/
int bisserch1(vector<int> data,int k,int left,int right){
if(left > right || data[left] > k|| data[right] <k){
return -5;
}else{
int mid = (left+right)/2;
if(data[right] == k){
return right;
}int dpi = bisserch1(data, k, mid+1, right);
if(dpi != -5){
return dpi;
}return bisserch1(data, k, left, mid);
}
}
/*方法3 :库函数 */
int origMethod(vector<int> data,int k){
auto result = equal_range(data.begin(),data.end(),k);
//second 左界,frist右界
return result.second - result.first;
}
};