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.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Solution {
6 public int[] TopKFrequent(int[] nums, int k) {
7 var freqMap = new Dictionary<int, int>();
8 foreach (var num in nums) {
9 if (!freqMap.ContainsKey(num))
10 freqMap[num] = 0;
11 freqMap[num]++;
12 }
13
14 return freqMap.OrderByDescending(x => x.Value).Take(k).Select(x => x.Key).ToArray();
15 }
16
17 public static void Main(string[] args) {
18 int[] nums = new int[] {1, 1, 1, 2, 2, 3};
19 int k = 2;
20 Solution sol = new Solution();
21 int[] result = sol.TopKFrequent(nums, k);
22 Console.WriteLine(string.Join(", ", result));
23 }
24}
25
We use a dictionary to count frequencies, then order by descending frequency and take 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).
1from collections import Counter
2
3def topKFrequent(nums, k):
4 count = Counter(nums)
5 buckets = [[] for _ in range(len(nums) + 1)]
6
7 for num, freq in count.items():
8 buckets[freq].append(num)
9
10 result = []
11 for i in range(len(buckets) - 1, 0, -1):
12 for num in buckets[i]:
13 result.append(num)
14 if len(result) == k:
15 return result
16
17if __name__ == '__main__':
18 nums = [1, 1, 1, 2, 2, 3]
19 k = 2
20 print(topKFrequent(nums, k))
21
Even with Python, we leverage frequency count with buckets to directly access and collect top k frequent elements.