Skip to content

Commit 6c4376e

Browse files
authored
Create yeongu.cpp
1 parent ec54f9b commit 6c4376e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

top-k-frequent-elements/yeongu.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// TC: O(n logn)
2+
// SC: O(n)
3+
4+
vector<int> topKFrequent(vector<int>& nums, int k) {
5+
unordered_map<int, int> frequency;
6+
for (int n : nums) {
7+
frequency[n] += 1;
8+
}
9+
auto comparator = [&frequency](int n1, int n2) {
10+
return frequency[n1] > frequency[n2];
11+
};
12+
13+
priority_queue<int, vector<int>, decltype(comparator)> min_heap(
14+
comparator);
15+
16+
for (auto& entry : frequency) {
17+
min_heap.push(entry.first);
18+
if (min_heap.size() > k) {
19+
min_heap.pop();
20+
}
21+
}
22+
23+
vector<int> output;
24+
25+
for (int i = 0; i < k; i++) {
26+
output.push_back(min_heap.top());
27+
min_heap.pop();
28+
}
29+
return output;
30+
}

0 commit comments

Comments
 (0)