https://leetcode-cn.com/problems/top-k-frequent-elements/
class Solution {
public:
struct Node {
int value;
int count;
Node() {
count = 0;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
std::unordered_map<int, Node> nums_count;
for (auto ite : nums) {
nums_count[ite].value = ite;
nums_count[ite].count++;
}
auto cmp = [](const Node& left, const Node& right) {
return left.count > right.count;
};
// 创建堆,优先级:次数最少的在堆顶top
priority_queue<Node, vector<Node>, decltype(cmp)> que(cmp);
for (auto ite : nums_count) {
if (que.size() < k) {
que.push(ite.second);
} else if (que.top().count < ite.second.count) {
que.pop();
que.push(ite.second);
}
}
vector<int> result;
while(!que.empty()) {
result.push_back(que.top().value);
que.pop();
}
std::reverse(std::begin(result), std::end(result));
return std::move(result);
}
};
class Compare {
public:
Compare(int key, int frequest) {
_key = key;
_frequest = frequest;
}
int _key;
int _frequest;
};
bool operator < (const Compare& a, const Compare& b) {
if (a._frequest >= b._frequest) {
return true;
}
return false;
}
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
std::unordered_map<int, int> k_map;
for (const auto& ite : nums) {
k_map[ite]++;
}
priority_queue<Compare> que;
for (const auto& ite : k_map) {
if (que.size() < k) {
que.push(Compare(ite.first, ite.second));
} else if (que.size() >= k && que.top()._frequest < ite.second) {
que.pop();
que.push(Compare(ite.first, ite.second));
} else {
continue;
}
}
vector<int> ret;
for (int i = 0; i < k ; ++i) {
ret.push_back(que.top()._key);
que.pop();
}
return ret;
}
};