top-k-frequent-elements 1.0.0
Top K Frequent Elements
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

vector< int > topKFrequent (vector< int > &nums, int k)
 

Detailed Description

Definition at line 5 of file main.cpp.

Member Function Documentation

◆ topKFrequent()

vector< int > Solution::topKFrequent ( vector< int > &  nums,
int  k 
)
inline

Definition at line 8 of file main.cpp.

9 {
10 unordered_map<int, int> occurrences; // (num, occurrences)
11 for (int el: nums)
12 occurrences[el]++;
13
14 auto comparator = [](pair<int, int>& A, pair<int, int>& B)
15 {
16 return A.second > B.second; // min-heap by frequency
17 };
18 priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comparator)> min_heap(comparator);
19
20 for (const pair<const int, int>& occ: occurrences)
21 {
22 min_heap.push(occ);
23 if ((int)min_heap.size() > k)
24 min_heap.pop(); // remove the least frequent element if size exceeds k
25 }
26
27 vector<int> answer;
28 while (!min_heap.empty())
29 {
30 answer.push_back(min_heap.top().first);
31 min_heap.pop();
32 }
33 return answer;
34 }

The documentation for this class was generated from the following file: