题目链接
开个哈希表,然后重写一下小于运算符,按照题意模拟即可
class Solution {
public:
struct node{
string s;
int cnt;
bool operator < (const node& t)const{
if(cnt != t.cnt) return cnt > t.cnt;
return s < t.s;
}
};
vector<node> v;
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> hash;
for(auto x : words) hash[x]++;
int idx = 0;
for(unordered_map<string,int>::iterator it = hash.begin(); it != hash.end(); it++)
{
auto x = *it;
v.push_back({x.first,x.second});
}
sort(v.begin(),v.end());
vector<string> ans;
for(int i = 0; i < k; i++) ans.push_back(v[i].s);
return ans;
}
};