Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
top-k-frequent-words.cpp 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-10-14 20:35 +08:00 . Update top-k-frequent-words.cpp
// Time: O(n + klogk) on average
// Space: O(n)
// Quick Select Solution
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> counts;
for (const auto& word : words) {
++counts[word];
}
vector<pair<int, string>> p;
for (const auto& kvp : counts) {
p.emplace_back(-kvp.second, kvp.first);
}
nth_element(p.begin(), p.begin() + k - 1, p.end()); // O(n) time on average.
sort(p.begin(), p.begin() + k); // O(klogk) time.
vector<string> result;
for (int i = 0; i < k; ++i) {
result.emplace_back(p[i].second);
}
return result;
}
};
// Time: O(nlogk)
// Space: O(n)
// Heap Solution
class Solution2 {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> counts;
for (const auto& word : words) {
++counts[word];
}
priority_queue<pair<int, string>> heap;
for (const auto& kvp : counts) {
heap.emplace(-kvp.second, kvp.first);
if (heap.size() == k + 1) {
heap.pop();
}
}
vector<string> result;
while (!heap.empty()) {
result.emplace_back(heap.top().second);
heap.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
// Time: O(n + klogk) ~ O(n + nlogn)
// Space: O(n)
// Bucket Sort Solution
class Solution3 {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> counts;
for (const auto& word : words) {
++counts[word];
}
vector<vector<string>> buckets(words.size() + 1);
for (const auto& kvp : counts) {
buckets[kvp.second].emplace_back(kvp.first);
}
vector<pair<int, string>> p;
for (int i = buckets.size() - 1; i >= 0; --i) {
for (const auto& word : buckets[i]) {
p.emplace_back(-i, word);
}
if (p.size() >= k) {
break;
}
}
sort(p.begin(), p.end());
vector<string> result;
for (int i = 0; i < k; ++i) {
result.emplace_back(p[i].second);
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助