-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthlargestNumberBasedonFreq.cpp
More file actions
82 lines (61 loc) · 2.13 KB
/
kthlargestNumberBasedonFreq.cpp
File metadata and controls
82 lines (61 loc) · 2.13 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
#include "import.h"
class Solution {
public:
vector<int> topKFrequentNthElement(vector<int>& nums, int k) {
unordered_map<int, int> counts;
for (const auto& i : nums)
{
++ counts[i];
}
vector<pair<int, int>> p;
for (auto it = counts.begin(); it != counts.end(); ++ it)
{
p.emplace_back(-(it->second), it->first);
}
nth_element(p.begin(), p.begin() + k - 1, p.end());
vector<int> result;
for (int i = 0; i < k; i++)
{
result.emplace_back(p[i].second);
}
return result;
}
vector<int> topKFrequentBS(vector<int>& nums, int k) {
unordered_map<int, int> mymap;
for(int num:nums){
mymap[num]++;
}
vector<vector<int>> bucket(nums.size()+1);
for(auto it =mymap.begin(); it!=mymap.end(); ++it){
int freq = it->second;
bucket[freq].push_back(it->first);
}
vector<int> result;
for (int pos = bucket.size() - 1; pos >= 0 && result.size() < k; pos--) {
if (!bucket[pos].empty()) {
for(int num:bucket[pos])
result.push_back(num);
if (result.size() == k)
break;
}
}
cout << result.size() << endl;
return result;
}
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mymap;
for(int num:nums){
mymap[num]++;
}
vector<int> result;
priority_queue<pair<int,int >> pq;
for(auto it =mymap.begin(); it!=mymap.end(); ++it){
pq.push(make_pair(it->second, it->first));
if(pq.size() > (int) mymap.size() - k){
result.push_back(pq.top().second);
pq.pop();
}
}
return result;
}
};