-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path347.cpp
More file actions
25 lines (23 loc) · 712 Bytes
/
Copy path347.cpp
File metadata and controls
25 lines (23 loc) · 712 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> hashmap;
for (int num : nums) {
auto pos = hashmap.find(num);
if (pos == hashmap.end()) hashmap[num] = 1;
pos->second += 1;
}
// 排序
vector<pair<int, int>> vec(hashmap.begin(), hashmap.end());
sort(vec.begin(), vec.end(), [](const pair<int, int> &a, const pair<int, int> &b) {
return b.second < a.second;
});
vector<int> res;
for (int i = 0; i < k; ++k) {
res.push_back(vec[i].first);
}
return res;
}
};