-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path347.cpp
More file actions
executable file
·84 lines (76 loc) · 1.99 KB
/
Copy path347.cpp
File metadata and controls
executable file
·84 lines (76 loc) · 1.99 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
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
#include <functional>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counter;
for (int num : nums){
counter[num]++;
}
vector<pair<int,int>> arr;
for (const auto& p : counter){
arr.push_back({p.second, p.first});
}
sort(arr.begin(), arr.end(), greater<>());
vector<int> result;
for (int i=0; i<k; i++){
result.push_back(arr[i].second);
}
return result;
}
};
// Min-Heap Solution
// TC = O(n logk)
// SC = O(n+k)
/* class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap;
for (auto& entry : count) {
heap.push({entry.second, entry.first});
if (heap.size() > k) {
heap.pop();
}
}
vector<int> res;
for (int i = 0; i < k; i++) {
res.push_back(heap.top().second);
heap.pop();
}
return res;
}
}; */
// Bucket-Sort
// TC - O(n)
// SC = O(n)
/* class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> count;
vector<vector<int>> freq(nums.size() + 1);
for (int n : nums) {
count[n] = 1 + count[n];
}
for (const auto& entry : count) {
freq[entry.second].push_back(entry.first);
}
vector<int> res;
for (int i = freq.size() - 1; i > 0; --i) {
for (int n : freq[i]) {
res.push_back(n);
if (res.size() == k) {
return res;
}
}
}
return res;
}
}; */