-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0692.cpp
More file actions
51 lines (42 loc) · 1.27 KB
/
Copy path0692.cpp
File metadata and controls
51 lines (42 loc) · 1.27 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
// sort: O(nlogn)
class Solution {
public:
vector<string> topKFrequent(const vector<string> &words, int k) {
unordered_map<string, int> um;
for (const auto &w : words)
um[w]++;
vector<pair<int, string>> vec(um.size());
vector<string> res(k);
int count = 0;
for (const auto &[k, v] : um)
vec[count++] = {-v, k};
sort(vec.begin(), vec.end());
for (int i = 0; i < k; i++)
res[i] = vec[i].second;
return res;
}
};
// heap: O(nlogk)
class Solution {
typedef pair<string, int> psi;
static constexpr const auto cmp = [](const psi &p1, const psi &p2) {
if (p1.second == p2.second) return p1.first < p2.first;
return p1.second > p2.second;
};
public:
vector<string> topKFrequent(const vector<string> &words, int k) {
unordered_map<string, int> um;
for (const auto &w : words)
um[w]++;
priority_queue<psi, vector<psi>, decltype(cmp)> pq(cmp);
vector<string> res(k);
for (auto it : um) {
pq.push(it);
if (pq.size() > k) pq.pop();
}
int count = k - 1;
while (!pq.empty())
res[count--] = pq.top().first, pq.pop();
return res;
}
};