Given an integer array nums and an integer k, return the k most frequent elements.
Solution in C++:
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> topKFrequent(vector<int>& nums, int k) {
// Count frequencies
unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
}
// Min heap: pair of (frequency, number)
// Compare by frequency (first element)
auto compare = [](pair<int, int>& a, pair<int, int>& b) {
return a.first > b.first; // Min heap: smaller frequency at top
};
priority_queue<pair<int, int>, vector<pair<int, int>>,
decltype(compare)> min_heap(compare);
// Keep k most frequent elements
for (auto& [num, freq] : count) {
if (min_heap.size() < k) {
min_heap.push({freq, num});
} else if (freq > min_heap.top().first) {
min_heap.pop();
min_heap.push({freq, num});
}
}
// Extract results
vector<int> result;
while (!min_heap.empty()) {
result.push_back(min_heap.top().second);
min_heap.pop();
}
return result;
}
Step-by-Step Simulation:
Input: nums = [1,1,1,2,2,3], k = 2
Frequencies: {1:3, 2:2, 3:1}
Processing:
num=1, freq=3: heap=[(3,1)]
num=2, freq=2: heap=[(2,2), (3,1)]
num=3, freq=1: heap=[(2,2), (3,1)] (1 < 2, skip)
Result: [2, 1] (most frequent)
Explanation: First, count frequencies using a hash map. Then use a min heap of size k to keep track of k most frequent elements. We compare by frequency. When we find an element with higher frequency than the smallest in the heap, we replace it. This ensures we always have the k most frequent elements. The min heap keeps the least frequent of the top k at the root.
Time Complexity: O(n + k log k)
Space Complexity: O(n)