lurenaa的博客

🉐查找 and 哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> count;
for(auto x :nums) {
count[x] += 1;
}
using value_t = pair<int, int>;
vector<value_t> container(count.begin(), count.end());
auto comp = [](const value_t &v1, const value_t &v2) {return v1.second < v2.second;};
make_heap(container.begin(), container.end(), comp);
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(container.begin()->first);
pop_heap(container.begin(), container.end() - i, comp);
}
return result;
}
};

Accepted

21/21 cases passed (24 ms)

Your runtime beats 62.88 % of cpp submissions

Your memory usage beats 9.89 % of cpp submissions (11.7 MB)