The trick here is to name the state correctly, then let the implementation follow. For 347. Top K Frequent Elements, the solution in this repository is mainly a heap / priority queue solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: heap / priority queue, greedy.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are operator, topKFrequent.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The queue gives the solution a level-by-level or frontier-style traversal.
- The heap keeps the best candidate available without sorting the whole world every time.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 24 ms, faster than 39.54% of C++ online submissions for Top K Frequent Elements.
02//Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions for Top K Frequent Elements.
03
04class valuecomparator
05{
06public:
07 valuecomparator(){}
08 bool operator() (const pair<int, int>& lhs, const pair<int, int>&rhs) const{
09 return lhs.second < rhs.second;
10 }
11};
12
13class Solution {
14public:
15 vector<int> topKFrequent(vector<int>& nums, int k) {
16 map<int, int> counter;
17 vector<int> ans;
18
19 for(int e : nums){
20 counter[e]++;
21 }
22
23 //cannot sort map!
24 // sort(counter.begin(), counter.end(),
25 // [](const pair<int, int>& a, const pair<int, int>& b){
26 // return a.second < b.second;
27 // });
28
29 priority_queue<pair<int, int>, vector<pair<int, int>>, valuecomparator> pq1;
30
31 for(auto it = counter.begin(); it != counter.end(); it++){
32 pq1.push(*it);
33 }
34
35 for(int i = 0; i < k; i++){
36 pair<int, int> p = pq1.top();
37 ans.push_back(p.first);
38 pq1.pop();
39 }
40
41 return ans;
42 }
43};
44
45//official solution
46//improve efficiency by keeping priority queue small
47//Runtime: 24 ms, faster than 39.54% of C++ online submissions for Top K Frequent Elements.
48//Memory Usage: 10.3 MB, less than 100.00% of C++ online submissions for Top K Frequent Elements.
49class valuecomparator
50{
51public:
52 valuecomparator(){}
53 bool operator() (const pair<int, int>& lhs, const pair<int, int>&rhs) const{
54 return lhs.second > rhs.second;
55 }
56};
57
58class Solution {
59public:
60 vector<int> topKFrequent(vector<int>& nums, int k) {
61 map<int, int> counter;
62 vector<int> ans(k);
63
64 for(int e : nums){
65 counter[e]++;
66 }
67
68 //the larger the lower
69 priority_queue<pair<int, int>, vector<pair<int, int>>, valuecomparator> pq1;
70
71 for(auto it = counter.begin(); it != counter.end(); it++){
72 pq1.push(*it);
73 //the smallest will be popped first
74 if(pq1.size() > k) pq1.pop();
75 }
76
77 //put into ans in reverse order
78 for(int i = k-1; i >= 0; i--){
79 pair<int, int> p = pq1.top();
80 ans[i] = p.first;
81 pq1.pop();
82 }
83
84 return ans;
85 }
86};
Cost