We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 608f0f8 commit 06628f3Copy full SHA for 06628f3
csharp/347-Top-K-Frequent-Elements.cs
@@ -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