-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution347.cs
43 lines (36 loc) · 1.05 KB
/
Solution347.cs
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
using System.Text;
namespace LeetCode.Solutions;
public class Solution347
{
/// <summary>
/// 347. Top K Frequent Elements - Medium
/// <a href="https://leetcode.com/problems/top-k-frequent-elements">See the problem</a>
/// </summary>
public int[] TopKFrequent(int[] nums, int k)
{
var frequency = new Dictionary<int, int>();
var bucket = new List<int>[nums.Length + 1];
var result = new List<int>();
foreach (var num in nums)
{
frequency[num] = frequency.GetValueOrDefault(num, 0) + 1;
}
foreach (var key in frequency.Keys)
{
var count = frequency[key];
if (bucket[count] == null)
{
bucket[count] = new List<int>();
}
bucket[count].Add(key);
}
for (var i = bucket.Length - 1; i >= 0 && result.Count < k; i--)
{
if (bucket[i] != null)
{
result.AddRange(bucket[i]);
}
}
return result.ToArray();
}
}