Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
k
个元素,当元素数超出 k
时则从堆中弹出最小元素。插入一个元素到堆的时间复杂度 O(log k)
,总体时间复杂度 O(n log k)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (auto& x : nums) {
++m[x];
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> q;
for (auto& x : m) {
q.emplace(x.second, x.first);
if (size(q) > k) {
q.pop();
}
}
vector<int> res;
while (!empty(q)) {
res.emplace_back(q.top().second);
q.pop();
}
return res;
}
};