题目链接

开个哈希表,然后重写一下小于运算符,按照题意模拟即可
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;
}
};
本文介绍如何使用哈希表优化数据结构,通过重写小于运算符,实现在给定字符串集合中找出频率最高的前k个字符串。适合那些对数据结构和算法感兴趣的开发者。
772

被折叠的 条评论
为什么被折叠?



