哈希表 + 小顶堆(优先队列)
#include <bits/stdc++.h>
using namespace std;
struct cmp
{
template <typename T, typename U>
bool operator()(T const &left, U const &right)
{
if (left.second < right.second)
return true;
return false;
}
};
int main()
{
string str;
int m;
map<int, int> mapping;
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
vector<int> res;
cin >> str;
cin >> m;
// input.
int i = 0, k = -1;
int len = str.length();
for (i = 0; i < len; i++)
{
if (str[i] == ',')
{
mapping[atoi(str.substr(k + 1, (i - k - 1)).c_str())] += 1;
k = i;
}
}
if (k < len - 1)
{
mapping[atoi(str.substr(k + 1, (i - k - 1)).c_str())] += 1;
}
// cal.
for (auto it = mapping.begin(); it != mapping.end(); ++it)
{
pq.push(make_pair(it->first, it->second));
}
while (pq.size() > mapping.size() - m)
{
res.push_back(pq.top().first);
pq.pop();
}
//print.
int j = 0;
for (j = 0; j < m - 1; j++)
cout << res[j] << ",";
cout << res[j];
system("pause");
return 0;
}