Skip to content

Commit 50bc649

Browse files
committed
top-k-frequent-elements
1 parent 913017b commit 50bc649

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

src/top-k-frequent-elements/bench.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
static void BM_solution(benchmark::State& state){
66
auto s = std::make_shared<Solution>();
77
for (auto _ : state) {
8-
8+
std::vector q = {1,1,1,2,2,3};
9+
s->topKFrequent(q, 2);
910
}
1011
}
1112

src/top-k-frequent-elements/solution.hpp

+28-1
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,36 @@
22

33
using namespace leetcode;
44

5+
6+
class Compare{
7+
public:
8+
bool operator()(const std::pair<int,int>& lhs, const std::pair<int,int>& rhs){
9+
return lhs.second > rhs.second;
10+
}
11+
};
12+
513
class Solution {
614
public:
715
std::vector<int> topKFrequent(std::vector<int>& nums, int k) {
8-
return {};
16+
std::unordered_map<int,int> map;
17+
for(auto num:nums){
18+
map[num]++;
19+
}
20+
21+
std::priority_queue<std::pair<int,int>, std::vector<std::pair<int,int>>, Compare> pq;
22+
for(auto item:map){
23+
pq.push(item);
24+
if(pq.size() > k){
25+
pq.pop();
26+
}
27+
}
28+
29+
std::vector<int> res(k);
30+
for(int i = k - 1; i >= 0 ; i--){
31+
res[i] = pq.top().first;
32+
pq.pop();
33+
}
34+
35+
return res;
936
}
1037
};

src/top-k-frequent-elements/test.cpp

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@
55

66
TEST_CASE(__FILE__){
77
auto s = std::make_shared<Solution>();
8-
8+
std::vector a = {1,2};
9+
std::vector q = {1,1,1,2,2,3};
10+
REQUIRE(s->topKFrequent(q, 2) == a);
911
}

0 commit comments

Comments
 (0)