Skip to content

Commit 742d19c

Browse files
authored
Merge pull request neetcode-gh#601 from KhaledSamir/khaled-topKElements
347-Top K Frequent Elements [CSharpSolution]
2 parents 39e8398 + 8803325 commit 742d19c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
3+
4+
namespace NeetCodeCSharpSolutions.ArraysHashing
5+
{
6+
public class Solution
7+
{
8+
public int[] TopKFrequent(int[] nums, int k)
9+
{
10+
var pq = new PriorityQueue<int, int>(new DescendingComparer());
11+
12+
var map = nums.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
13+
14+
foreach (var kv in map)
15+
{
16+
pq.Enqueue(kv.Key, kv.Value);
17+
}
18+
19+
var ans = new List<int>();
20+
while (k-- > 0)
21+
{
22+
ans.Add(pq.Dequeue());
23+
}
24+
25+
return ans.ToArray();
26+
}
27+
28+
public class DescendingComparer : IComparer<int>
29+
{
30+
public int Compare(int x, int y)
31+
{
32+
return y.CompareTo(x);
33+
}
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)