时间轴

2026-03-19

init


题目:

大顶堆

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
#include <vector>
#include <unordered_map>
#include <queue>
#include <utility>

using std::vector;
using std::unordered_map;
using std::priority_queue;
using std::pair;

class Solution {
public:
vector<int> topKFrequent(vector<int> &nums, int k)
{
vector<int> res;
unordered_map<int, int> umap;
priority_queue<pair<int, int>, vector<pair<int, int> >, std::less<pair<int, int> > >
max_heap;

for (int val : nums)
umap[val]++;

for (auto [val, times] : umap)
max_heap.push({ times, val });

while (k > 0) {
res.push_back(max_heap.top().second);
max_heap.pop();
k--;
}

return res;
}
};

实际上最优解是用快速排序:

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
#include <vector>
#include <unordered_map>
#include <utility>

using std::pair;
using std::vector;
using std::unordered_map;

class Solution {
private:
void quick_sort(vector<pair<int, int> > &arr, int k, int start, int end)
{
if (start >= end)
return;
int pivot = arr[(start + end) / 2].first;
int left = start - 1;
int right = end + 1;

while (left < right) {
do {
left++;
} while (arr[left].first > pivot);

do {
right--;
} while (arr[right].first < pivot);

if (left < right)
std::swap(arr[left], arr[right]);
}

// start ..=right, right+1..=end
if (k <= right)
quick_sort(arr, k, start, right);
else
quick_sort(arr, k, right + 1, end);
}

public:
vector<int> topKFrequent(vector<int> &nums, int k)
{
int i;
vector<pair<int, int> > arr;
unordered_map<int, int> umap;
vector<int> res;

for (int val : nums)
umap[val]++;

for (auto [val, times] : umap)
arr.push_back({ times, val });

quick_sort(arr, k, 0, arr.size() - 1);

for (i = 0; i < k; i++)
res.push_back(arr[i].second);

return res;
}
};