-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop_k_frequent_elements.cpp
More file actions
68 lines (62 loc) · 1.69 KB
/
top_k_frequent_elements.cpp
File metadata and controls
68 lines (62 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* =====================================================================================
*
* Filename: top_k_frequent_elements.cpp
*
* Description: 347. Top K Frequent Elements.
* https://leetcode.com/problems/top-k-frequent-elements/
*
* Version: 1.0
* Created: 03/07/23 16:07:19
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <queue>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::pair;
using std::priority_queue;
using std::tuple;
using std::unordered_map;
using std::vector;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (const int n : nums) {
counts[n]++;
}
auto compare = [&](const int a, const int b) -> bool {
return counts[a] < counts[b];
};
priority_queue<int, vector<int>, decltype(compare)> pq(compare);
for (const auto& kv : counts) {
pq.push(kv.first);
}
vector<int> res;
while (k-- > 0) {
res.push_back(pq.top());
pq.pop();
}
return res;
}
};
TEST(Solution, topKFrequent) {
vector<tuple<vector<int>, int, vector<int>>> cases = {
std::make_tuple(vector<int>{1}, 1, vector<int>{1}),
std::make_tuple(vector<int>{1, 1, 1, 2, 2, 3}, 2, vector<int>{1, 2}),
};
for (auto& c : cases) {
EXPECT_THAT(Solution().topKFrequent(std::get<0>(c), std::get<1>(c)),
testing::ElementsAreArray(std::get<2>(c)));
}
}