思路1
- 使用hashmap记录单词频率
- 创建
vector<string>
根据hashmap进行排序 - 根据要求对特定的vector进行提取,或者原地erase不需要的元素
代码1
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> hashmap;
for(string item:words)
hashmap[item]++;
vector<string> ans;
for(auto iter=hashmap.begin();iter!=hashmap.end();iter++)
ans.emplace_back(iter->first);
sort(ans.begin(),ans.end(),[&](const string&p1,const string &p2)->bool{
if(hashmap[p1]!=hashmap[p2])
return hashmap[p1] > hashmap[p2];
else
return p1 < p2;
});
ans.erase(ans.begin()+k,ans.end());
return ans;
}
};
思路2
- 使用hashmap记录单词频率
- 创建优先队列进行hashmap排序 元素提取
- 创建
vector<string>
对优先队列第一个元素进行提取
代码2
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto word : words)
cnt[word]++;
auto cmp = [](const pair<string, int>& a, const pair<string, int>& b) {
return a.second == b.second ? a.first < b.first : a.second > b.second;
};
priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> que(cmp);
for (auto it : cnt) {
que.emplace(it);
if (que.size() > k)
que.pop();
}
vector<string> ret(k);
for (int i = k - 1; i >= 0; i--) {
ret[i] = que.top().first;
que.pop();
}
return ret;
}
};