1. 题目来源
链接:692. 前K个高频单词
2. 题目解析
STL
应用。自定义排序即可,也可以直接用 priority_queue<pair<string, int>>
堆来处理本题。
时间复杂度:
O
(
n
l
o
g
n
)
O(nlogn)
O(nlogn)
空间复杂度:
O
(
n
)
O(n)
O(n)
代码:
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> hs;
for (auto &e : words) hs[e] ++ ;
vector<pair<string, int>> a;
for (auto &e : hs) a.push_back({e.first, e.second});
sort(a.begin(), a.end(), [](pair<string, int> a, pair<string, int> b) {
if (a.second == b.second) return a.first < b.first;
return a.second > b.second;
});
vector<string> res;
for (int i = 0; i < k; i ++ ) res.push_back(a[i].first);
return res;
}
};
堆,摘自评论区代码:
#define PSI pair<string, int>
class Solution {
private:
struct cmp {
bool operator ()(PSI& a, PSI& b) {
return a.second == b.second ? a.first < b.first : a.second > b.second;
}
};
public:
vector<string> topKFrequent(vector<string>& words, int k) {
int n = words.size();
unordered_map<string, int> hash;
for (auto& e : words) {
++hash[s];
}
priority_queue<PSI, vector<PSI>, cmp> que;
for (auto& i : hash) {
que.emplace(i);
if (que.size() > k) {
que.pop();
}
}
vector<string> ans(k);
for (int i = k - 1; i >= 0; --i) {
ans[i] = que.top().first;
que.pop();
}
return ans;
}
};