目录
一、题目描述
给一非空的单词列表,返回前 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) 空间复杂度解决。
二、解题思路
这道题的标签是字典树,可以做,但是没有必要。没有必要的原因在于寻找前K个的单词的操作,字典树并不擅长。只能把字典树遍历一遍然后使用另外的结构统计次数的排序。
那为什么不直接使用其他的结构来做呢,标准库完全可以在同等时间和空间开销内达到要求。
所以这是一道标准可的应用题,搞简单点呗。
- 使用哈希表统计所有单词的出现次数;
- 将哈希表的内容放进数组里;
- 数组自定义排序,然后输出前k个单词即可。
三、代码实现
/*!
* \file main.cpp
*
* \author 90826
* \date 一月 2021
*
* 力扣692:前K个高频单词
* 标签是字典树,但是没有必要,并没有多便利
* 还不如使用哈希表+自定义排序(STD应用题)
*/
#include<bits/stdc++.h>
using namespace std;
static bool cmp(pair<string, int>& a, pair<string, int>& b) {
return a.second != b.second ? a.second > b.second: a.first < b.first ;
}
vector<string> topKFrequent(vector<string>& words, int k) {
int n = words.size();
unordered_map<string, int> strMap;
for (auto &x : words) {
strMap[x]++;
}
vector<pair<string, int>> strVec;
for (auto ite = strMap.begin(); ite != strMap.end(); ite++) {
strVec.push_back({ite->first, ite->second});
}
sort(strVec.begin(), strVec.end(), cmp);
vector<string> res;
for (int i = 0; i < k; i++) {
res.push_back(strVec[i].first);
}
return res;
}
int main() {
vector<string> words = { "i", "love", "leetcode", "i", "love", "coding" };
int k = 2;
words = topKFrequent(words, k);
for (auto &x : words) {
cout << x << " ";
}
return 0;
}