Skip to content

Commit 06628f3

Browse files
committed
Add csharp solution for Top K Frequent Elements
1 parent 608f0f8 commit 06628f3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Diff for: csharp/347-Top-K-Frequent-Elements.cs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution {
2+
public int[] TopKFrequent(int[] nums, int k) {
3+
int[] arr = new int[k];
4+
var dict = new Dictionary<int, int>();
5+
for (int i = 0; i < nums.Length; i++)
6+
{
7+
if (dict.ContainsKey(nums[i]))
8+
{
9+
dict[nums[i]]++;
10+
}
11+
else
12+
{
13+
dict.Add(nums[i], 1);
14+
}
15+
}
16+
17+
var pq = new PriorityQueue<int, int>();
18+
foreach (var key in dict.Keys)
19+
{
20+
pq.Enqueue(key, dict[key]);
21+
if (pq.Count > k) pq.Dequeue();
22+
}
23+
int i2 = k;
24+
while (pq.Count > 0) {
25+
arr[--i2] = pq.Dequeue();
26+
}
27+
return arr;
28+
}
29+
}

0 commit comments

Comments
 (0)