Leetcode 347. Top K Frequent Elements
Given a non-empty array of integers, you need to return the k
most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
k
is always valid, 1 ≤ k ≤ number of unique elements
.O(n log n)
, where n is the array’s size.unordered_map
).k
elements.This approach guarantees that we can handle the required time complexity better than O(n log n)
.
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// Step 1: Count the frequency of each element
unordered_map<int, int> frequencyMap;
for (int num : nums) {
frequencyMap[num]++;
}
// Step 2: Create buckets where index represents frequency
int n = nums.size();
vector<vector<int>> buckets(n + 1);
for (auto& pair : frequencyMap) {
int frequency = pair.second;
int number = pair.first;
buckets[frequency].push_back(number);
}
// Step 3: Collect the top k frequent elements
vector<int> result;
for (int i = n; i >= 0 && result.size() < k; --i) {
if (!buckets[i].empty()) {
for (int num : buckets[i]) {
result.push_back(num);
if (result.size() == k) {
return result;
}
}
}
}
return result;
}
};
O(n)
time to count the frequency of each element.O(n)
time.k
elements takes O(n)
time in the worst case where all elements are unique and we might have to look in every bucket.Overall, the time complexity is O(n)
, which is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?