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).
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.