Sponsored
Sponsored
This approach uses a hash map to count the frequency of each element. We then use a min-heap to keep track of the top k elements.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing frequencies.
1from collections import Counter
2import heapq
3
4def topKFrequent(nums, k):
5 count = Counter(nums)
6 return heapq.nlargest(k, count.keys(), key=count.get)
7
8if __name__ == '__main__':
9 nums = [1,1,1,2,2,3]
10 k = 2
11 print(topKFrequent(nums, k))
12We use Python's collections.Counter and heapq.nlargest functions to efficiently get the top k frequent elements.
This approach involves using bucket sort where we create buckets for frequency counts and then extract the top k frequent elements.
Time Complexity: O(n + k).
Space Complexity: O(n).
1#include <iostream>
2#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> freqMap;
vector<vector<int>> buckets(nums.size() + 1);
for (int num : nums) {
freqMap[num]++;
}
for (auto& p : freqMap) {
buckets[p.second].push_back(p.first);
}
vector<int> result;
for (int i = buckets.size() - 1; i >= 0 && result.size() < k; --i) {
for (int num : buckets[i]) {
result.push_back(num);
if (result.size() == k) break;
}
}
return result;
}
int main() {
vector<int> nums = {1, 1, 1, 2, 2, 3};
int k = 2;
vector<int> result = topKFrequent(nums, k);
for (int num : result) {
cout << num << " ";
}
return 0;
}
Frequency occurrences are placed in buckets. The largest buckets represent the most frequent elements.