-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path347.cpp
More file actions
70 lines (64 loc) · 1.48 KB
/
Copy path347.cpp
File metadata and controls
70 lines (64 loc) · 1.48 KB
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
61
62
63
64
65
66
67
68
69
70
#include "common.h"
using namespace std;
class Solution {
unordered_map<int, int> counts;
public:
int partition(vector<int>& uni_nums, int l, int r) {
if (l == r) {
return l;
}
int pivot = (l + r) / 2;
swap(uni_nums[pivot], uni_nums[r]);
int i, j;
i = j = l;
while (j < r) {
if (counts[uni_nums[j]] < counts[uni_nums[r]]) {
swap(uni_nums[j], uni_nums[i++]);
}
j += 1;
}
swap(uni_nums[i], uni_nums[r]);
return i;
}
void quickSelect(vector<int>& uni_nums, int l, int r, int count) {
if (l == r) {
return;
}
int pivot = partition(uni_nums, l, r);
while (pivot != count) {
if (pivot < count) {
l = pivot + 1;
} else {
r = pivot - 1;
}
pivot = partition(uni_nums, l, r);
}
}
vector<int> topKFrequent(vector<int>& nums, int k) {
for (auto n : nums) {
counts[n] += 1;
}
vector<int> uni_nums;
uni_nums.reserve(counts.size());
for (auto n : counts) {
uni_nums.push_back(n.first);
}
if (uni_nums.size() == k) {
return uni_nums;
}
quickSelect(uni_nums, 0, uni_nums.size() - 1, uni_nums.size() - k);
vector<int> rst(k);
copy(uni_nums.begin() + uni_nums.size() - k, uni_nums.end(), rst.begin());
return rst;
}
};
int main() {
Solution s;
vector<int> v = {5, 3, 1, 1, 1, 3, 73, 1};
auto rst = s.topKFrequent(v, 2);
for (auto n : rst) {
cout << n << ", ";
}
cout << endl;
return 0;
}