题目来源:leetcode
class Solution {
public:
struct MapCompare
{
bool operator()(map<string,int>::iterator x,map<string,int>::iterator y)
{
return x->second < y->second;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
map<string,int> countmap;
for(auto& e: words)
{
countmap[e]++;
}
// vector<map<string,int>::iterator> v;
// map<string,int>::iterator mapit = countmap.begin();
// while(mapit != countmap.end())
// {
// v.push_back();
// mapit++;
// }
// //sort 的底层是快排,快排是不稳定的,解决不了
// sort(v.begin(),v.end(),MapCompare());
// vector<string> retv;
// for(int i = 0;i < k;i++)
// {
// retv.push_back(v[i]->first);
// }
// return retv;
//使用map/multimap的特性进行排序,是稳定的
multimap<int ,string,greater<int>> sortmap;//排降序
for(auto e : countmap)
{
sortmap.insert(make_pair(e.second,e.first));
}
vector<string> retv;
auto rit = sortmap.begin();
while(k--)
{
retv.push_back(rit->second);
rit++;
}
return retv;
}
};