-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop-k-frequent-elements.cpp
66 lines (52 loc) · 1.38 KB
/
top-k-frequent-elements.cpp
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
/*
* Copyright (c) 2018 Christopher Friedt
*
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
// https://leetcode.com/problems/top-k-frequent-elements/
vector<int> topKFrequent(vector<int> &nums, int k) {
vector<int> r;
unordered_map<int, size_t> count;
// Insertion in a hash table is O( 1 ), so multiply by N
for (auto &n : nums) {
if (count.end() == count.find(n)) {
count[n] = 1;
} else {
count[n]++;
}
}
struct gt {
// return true if b > a
bool operator()(const pair<size_t, int> &a, const pair<size_t, int> &b) {
return b.second > a.second;
}
};
// max heap / priority queue for the histogram
vector<pair<int, size_t>> heap;
// average case O( 1 ), worst O( n ) but only when all items are equal
// which they are not
for (auto &kv : count) {
heap.push_back(kv);
push_heap(heap.begin(), heap.end(), gt());
}
for (size_t i = 0; (int)i < k; i++) {
if (heap.empty()) {
break;
}
pop_heap(heap.begin(), heap.end(), gt());
pair<int, size_t> highest_pair = heap.back();
int highest_int = highest_pair.first;
heap.pop_back();
r.push_back(highest_int);
}
return r;
}
};