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.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4#include <queue>
5
6using namespace std;
7
8vector<int> topKFrequent(vector<int>& nums, int k) {
9 unordered_map<int, int> freqMap;
10 for (int num : nums) {
11 freqMap[num]++;
12 }
13
14 auto compare = [&](int a, int b) { return freqMap[a] > freqMap[b]; };
15 priority_queue<int, vector<int>, decltype(compare)> minHeap(compare);
16
17 for (auto& p : freqMap) {
18 minHeap.push(p.first);
19 if (minHeap.size() > k) {
20 minHeap.pop();
21 }
22 }
23
24 vector<int> result;
25 while (!minHeap.empty()) {
26 result.push_back(minHeap.top());
27 minHeap.pop();
28 }
29 return result;
30}
31
32int main() {
33 vector<int> nums = {1, 1, 1, 2, 2, 3};
34 int k = 2;
35 vector<int> result = topKFrequent(nums, k);
36 for (int num : result) {
37 cout << num << " ";
38 }
39 return 0;
40}
41We use a hash map to count frequencies, then use a min-heap of size k to keep track of the top k 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).
1using System;
2using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] TopKFrequent(int[] nums, int k) {
var freqMap = new Dictionary<int, int>();
foreach (var num in nums) {
if (!freqMap.ContainsKey(num))
freqMap[num] = 0;
freqMap[num]++;
}
List<int>[] buckets = new List<int>[nums.Length + 1];
foreach (var pair in freqMap) {
int freq = pair.Value;
if (buckets[freq] == null)
buckets[freq] = new List<int>();
buckets[freq].Add(pair.Key);
}
List<int> res = new List<int>();
for (int i = buckets.Length - 1; i >= 0 && res.Count < k; --i) {
if (buckets[i] != null)
res.AddRange(buckets[i].ToArray());
}
return res.Take(k).ToArray();
}
public static void Main(string[] args) {
int[] nums = new int[] {1, 1, 1, 2, 2, 3};
int k = 2;
Solution sol = new Solution();
int[] result = sol.TopKFrequent(nums, k);
Console.WriteLine(string.Join(", ", result));
}
}
In this C# implementation, frequency of elements is handled with lists representing buckets, aiding the direct extraction of frequent elements.