-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0347_topKFrequent.cc
89 lines (80 loc) · 1.38 KB
/
Problem_0347_topKFrequent.cc
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
private:
class Node
{
public:
int num;
int count;
Node()
{
num = -1;
count = -1;
}
Node(int k)
{
num = k;
count = 1;
}
bool operator<(const Node &other) const { return this->count > other.count; }
};
public:
vector<int> topKFrequent(vector<int> &nums, int k)
{
unordered_map<int, Node> map;
for (int num : nums)
{
if (!map.count(num))
{
map.emplace(num, Node(num));
}
else
{
map[num].count++;
}
}
// 小根堆
priority_queue<Node> q;
for (auto &[_, node] : map)
{
if (q.size() < k || (q.size() == k && node.count > q.top().count))
{
q.push(node);
}
if (q.size() > k)
{
q.pop();
}
}
vector<int> ans(k);
int index = k-1;
while (!q.empty())
{
ans[index--] = q.top().num;
q.pop();
}
return ans;
}
};
void testTopKFrequent()
{
Solution s;
vector<int> n1 = {1, 1, 1, 2, 2, 3};
vector<int> o1 = {1, 2};
vector<int> n2 = {1};
vector<int> o2 = {1};
EXPECT_TRUE(o1 == s.topKFrequent(n1, 2));
EXPECT_TRUE(o2 == s.topKFrequent(n2, 1));
EXPECT_SUMMARY;
}
int main()
{
testTopKFrequent();
return 0;
}