Skip to content

Commit a142098

Browse files
[Neetcode] Top K Frequent Elements
1 parent d270c8a commit a142098

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

Neetcode/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
cmake_minimum_required(VERSION 3.12)
22
project(Neetcode)
33

4-
set(CMAKE_CXX_STANDARD 20)
4+
set(CMAKE_CXX_STANDARD 17)
55

66
add_executable(Two_sum_neetcode "Two sum/Two sum.cpp")
77
add_executable(Group_anagrams_neetcode "Group anagrams/Group anagrams.cpp")
8+
add_executable(Top_K_Frequent_Elements "Top K Frequent Elements/Top K Frequent Elements.cpp")
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <algorithm>
2+
#include <iostream>
3+
#include <limits>
4+
#include <optional>
5+
#include <unordered_map>
6+
#include <vector>
7+
8+
class Solution {
9+
public:
10+
std::vector<int> topKFrequent(std::vector<int> &nums, int k);
11+
};
12+
13+
std::vector<int> Solution::topKFrequent(std::vector<int> &nums, int k) {
14+
std::unordered_map<int, std::size_t> freq_table;
15+
for (const auto num : nums) {
16+
++freq_table[num];
17+
}
18+
19+
std::vector<std::vector<int>> freq_order(nums.size() + 1);
20+
for (const auto &kv : freq_table) {
21+
const auto &value = kv.first;
22+
const auto &freq = kv.second;
23+
freq_order[freq].emplace_back(value);
24+
}
25+
26+
std::vector<int> k_freq;
27+
k_freq.reserve(k);
28+
for (auto i_it = freq_order.rbegin(); i_it != freq_order.rend(); ++i_it) {
29+
if (i_it->empty()) {
30+
continue;
31+
}
32+
33+
for (auto j_it = i_it->begin(); j_it != i_it->end() && k > 0; ++j_it, --k) {
34+
k_freq.emplace_back(*j_it);
35+
}
36+
}
37+
return k_freq;
38+
}
39+
40+
int main(int argc, char *argv[]) {
41+
std::vector nums{1, 2, 2, 3, 3, 3};
42+
auto k = 2;
43+
for (const auto num : Solution().topKFrequent(nums, k)) {
44+
std::cout << num << std::endl;
45+
}
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)