1.问题描述
算法面试题汇总 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台
2.代码
struct Less {
bool operator() (const std::pair<int, int>& e1, const std::pair<int, int>& e2) const {
return e1.second < e2.second;
}
};
class Solution {
public:
vector<int> topKFrequent1(vector<int>& nums, int k) {
stat_map.clear();
for (auto &num : nums) {
auto it = stat_map.find(num);
if (it == stat_map.end()) {
stat_map.emplace(num, 1);
}
else {
++(it->second);
}
}
vec.clear();
for (const auto &m : stat_map) {
vec.push_back(m);
}
sort(vec.begin(), vec.end(), [] (const std::pair<int, int>& e1, const std::pair<int, int>& e2) { return e1.second > e2.second; } );
std::vector<int>tmp;
for (int i = 0;(i < k) && (i < vec.size());i++) {
tmp.push_back(vec[i].first);
}
return tmp;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
stat_map.clear();
for (auto &num : nums) {
auto it = stat_map.find(num);
if (it == stat_map.end()) {
stat_map.emplace(num, 1);
}
else {
++(it->second);
}
}
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, Less>pq;
for (const auto &m : stat_map) {
pq.push(m);
}
if (k > pq.size()) {
k = pq.size();
}
std::vector<int>tmp;
for (int i = 0;i < k;i++) {
tmp.push_back(pq.top().first);
pq.pop();
}
return tmp;
}
private:
std::unordered_map<int, int>stat_map;
std::vector<std::pair<int, int> >vec;
};
3.运行
4.使用模板抽象
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
template <class T>
struct Less {
bool operator() (const std::pair<T, int>& e1, const std::pair<T, int>& e2) const {
return e1.second < e2.second;
}
};
template <class T>
class top_k_solution {
public:
static std::vector<T> top_k(std::vector<T>& elements, int k) {
std::unordered_map<T, int>stat_map;
for (auto &e : elements) {
auto it = stat_map.find(e);
if (it == stat_map.end()) {
stat_map.emplace(e, 1);
}
else {
++(it->second);
}
}
std::priority_queue<std::pair<T, int>, std::vector<std::pair<T, int>>, Less<T>>pq;
for (const auto &m : stat_map) {
pq.push(m);
}
if (k > pq.size()) {
k = pq.size();
}
std::vector<T>tmp;
for (int i = 0;i < k;i++) {
tmp.emplace_back(pq.top().first);
pq.pop();
}
return tmp;
}
};