Skip to content

Commit 731e050

Browse files
committed
Add step4
1 parent 769fee7 commit 731e050

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

347/step4.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
priority_queueの最大サイズを制限する
3+
*/
4+
class Solution {
5+
public:
6+
vector<int> topKFrequent(vector<int>& nums, int k) {
7+
map<int, int> num_to_count;
8+
for (int num: nums) {
9+
num_to_count[num]++;
10+
}
11+
12+
priority_queue<NumCount, vector<NumCount>, greater<NumCount>> num_count;
13+
for (auto [num, count] : num_to_count) {
14+
num_count.push({num, count});
15+
if (num_count.size() > k) {
16+
num_count.pop();
17+
}
18+
}
19+
20+
vector<int> answer;
21+
for (int i = 0; i < k; i++) {
22+
answer.push_back(num_count.top().num);
23+
num_count.pop();
24+
}
25+
return answer;
26+
}
27+
28+
private:
29+
struct NumCount {
30+
int num;
31+
int count;
32+
33+
bool operator> (const NumCount& other) const {
34+
return count > other.count;
35+
}
36+
};
37+
};

0 commit comments

Comments
 (0)