We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ec54f9b commit 6c4376eCopy full SHA for 6c4376e
top-k-frequent-elements/yeongu.cpp
@@ -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
28
29
+ return output;
30
+}
0 commit comments