-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopKFrequentElements.cs
More file actions
64 lines (55 loc) · 2.27 KB
/
TopKFrequentElements.cs
File metadata and controls
64 lines (55 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
namespace Solutions.Problems;
public class TopKFrequentElementsSolution
{
/// <summary>
/// Sorting the elements by their frequency and returning the k most frequent elements.
/// </summary>
/// <param name="nums">The array of integers.</param>
/// <param name="k">The number of top frequent elements to return.</param>
/// <returns>An array of the k most frequent elements.</returns>
public int[] TopKFrequent(int[] nums, int k) =>
[.. nums.CountBy(n => n)
.OrderByDescending(g => g.Value)
.Take(k)
.Select(g => g.Key)];
/// <summary>
/// Using a min-heap (priority queue) to keep track of the top k frequent elements.
/// </summary>
/// <param name="nums">The array of integers.</param>
/// <param name="k">The number of top frequent elements to return.</param>
/// <returns>An array of the k most frequent elements.</returns>
public int[] TopKFrequentHeap(int[] nums, int k)
{
var freq = nums.CountBy(n => n)
.ToDictionary(g => g.Key, g => g.Value);
var pq = new PriorityQueue<int, int>();
foreach (var kv in freq)
{
pq.Enqueue(kv.Key, kv.Value);
if (pq.Count > k)
pq.Dequeue();
}
var result = new int[k];
for (int i = 0; i < k; i++)
result[i] = pq.Dequeue();
return result;
}
/// <summary>
/// Using bucket sort to group elements by their frequency and then returning the k most frequent elements.
/// </summary>
/// <param name="nums">The array of integers.</param>
/// <param name="k">The number of top frequent elements to return.</param>
/// <returns>An array of the k most frequent elements.</returns>
public int[] TopKFrequentBucket(int[] nums, int k)
{
var freq = nums.CountBy(n => n)
.ToDictionary(g => g.Key, g => g.Value);
List<int>[] buckets = [.. Enumerable.Range(0, nums.Length + 1)
.Select(_ => new List<int>())];
foreach (var kv in freq)
buckets[kv.Value].Add(kv.Key);
return [.. buckets.Reverse()
.SelectMany(b => b)
.Take(k)];
}
}