692. 前K个高频单词
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
注意:
- 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
- 输入的单词均由小写字母组成。
扩展练习:
- 尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。
第一版,用优先队列解决问题
执行用时 :20 ms, 在所有 cpp 提交中击败了86.48%的用户
内存消耗 :11.4 MB, 在所有 cpp 提交中击败了86.59%的用户
structcompare {
booloperator()(constpair<string, int>&a, constpair<string, int>&b) {
if (a.second==b.second)
returna<b;
returna.second>b.second;
}
};
vector<string>topKFrequent(vector<string>&words, intk) {
unordered_map<string, int>result(words.size());
for (auto&a : words) {
result[a]++;
}
priority_queue<pair<string, int>, vector<pair<string, int>>, compare>pri_que;
for (auto&a : result) {
pri_que.push(a);
if (pri_que.size() >k)
pri_que.pop();
}
vector<string>res;
res.reserve(k);
while (!pri_que.empty()) {
res.push_back(pri_que.top().first);
pri_que.pop();
}
reverse(res.begin(), res.end()); //注意翻转一下
returnres;
}
第二版,不用优先队列其实更快一点
执行用时 :12 ms, 在所有 cpp 提交中击败了99.81%的用户
内存消耗 :11.1 MB, 在所有 cpp 提交中击败了97.56%的用户
boolstaticcompare(constpair<string, int>&a, constpair<string, int>&b) {
if (a.second==b.second)
returna<b;
returna.second>b.second;
}
vector<string>topKFrequent(vector<string>&words, intk) {
unordered_map<string, int>result(words.size());
for (auto&a : words) {
result[a]++;
}
vector<pair<string, int>>res;
res.assign(result.begin(), result.end());
sort(res.begin(), res.end(), compare);
vector<string>resTemp;
resTemp.reserve(k);
autobeg=res.begin();
while (k--) {
resTemp.push_back(beg->first);
++beg;
}
returnresTemp;
}