31.数字在排序数组中出现的次数
题目内容:
代码及思路:
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution
{
public:
int GetNumberOfK(vector<int> data, int k)
{
//因为是排序的,使用哈希表
unordered_map<int, int> hash;
for (int i = 0; i < data.size(); i++)
{
hash[data[i]]++;
}
return hash[k];
}
};
void main()
{
vector<int> data;
int num;
char ch;
do
{
cin >> num;
data.push_back(num);
cin.get(ch);
} while (ch == ',');
int k;
cin >> k;
Solution* object = new Solution;
int res = object->GetNumberOfK(data, k);
cout << res << endl;
}