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.
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}
25We 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).
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.