File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments