generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem47.cs
More file actions
48 lines (41 loc) · 1.29 KB
/
Problem47.cs
File metadata and controls
48 lines (41 loc) · 1.29 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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/top-k-frequent-elements/">Top K Frequent Elements</see>.
/// </summary>
public static class Problem47
{
/// <summary>
/// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
/// Time complexity: O(k log d).
/// Space complexity: O(d).
/// </summary>
/// <param name="nums">Array to traverse.</param>
/// <param name="k">k most frequent elements to return.</param>
/// <returns>k most frequent elements.</returns>
public static int[] TopKFrequent(int[] nums, int k)
{
var dict = new Dictionary<int, int>();
foreach (var num in nums)
{
if (dict.ContainsKey(num))
{
dict[num]++;
}
else
{
dict.Add(num, 1);
}
}
var heap = new BinaryHeap<int>(Comparer<int>.Create((a, b) => dict[a].CompareTo(dict[b])), dict.Keys.Count);
foreach (var num in dict.Keys)
{
heap.Enqueue(num);
}
var result = new int[k];
for (var i = 0; i < result.Length; i++)
{
result[i] = heap.Dequeue();
}
return result;
}
}