题目大意:
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。
来源:力扣(LeetCode
)
链接:https://leetcode-cn.com/problems/top-k-frequent-words/
解决思路:
首先使用HashMap记录每个单词的编号,然后统计每个单词的数目,最后按照题目意思排序即可。
时间复杂度:O(n log k) 空间复杂度:O(n)
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
struct node{
string a;
int num;
node() {
a = "", num = 0;
}
bool operator< (const node & x) const{
if (num != x.num)
return num > x.num;
return a < x.a;
}
};
unordered_map<string, int> mp;
node *p = new node[words.size()];
int pnum = 0;
vector<string> ans;
for (auto s: words) {
if (!mp.count(s)) {
mp[s] = pnum++;
p[mp[s]].a = s;
}
p[mp[s]].num++;
}
sort(p, p + pnum);
for (int i = 0; i < k; i++) {
ans.push_back(p[i].a);
}
return ans;
}
};