|
Q: Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2: Input: nums = [1], k = 1 Output: [1]
Example 3: Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2 Output: [1,2]
Constraints: - 1 <= nums.length <= 105
- -104 <= nums <= 104
- k is in the range [1, the number of unique elements in the array].
- It is guaranteed that the answer is unique.
A:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
vector<int> topKFrequent(vector<int>& nums, int k) {
// Step 1: Count the frequency of each element
unordered_map<int, int> freq_map;
for (int num : nums) {
freq_map[num]++;
}
// Step 2: Use a min-heap to keep the k most frequent elements
// Priority queue stores pairs: (-frequency, element), we negate the frequency
// to simulate a max-heap using a min-heap.
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap;
for (const auto& entry : freq_map) {
min_heap.push({entry.second, entry.first});
// If heap size exceeds k, pop the least frequent element
if (min_heap.size() > k) {
min_heap.pop();
}
}
// Step 3: Extract the top k elements from the heap
vector<int> result;
while (!min_heap.empty()) {
result.push_back(min_heap.top().second);
min_heap.pop();
}
return result;
}
|