forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
37 lines (34 loc) · 1.29 KB
/
Solution.cs
File metadata and controls
37 lines (34 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
namespace LeetCodeNet.G0301_0400.S0347_top_k_frequent_elements {
// #Medium #Top_100_Liked_Questions #Array #Hash_Table #Sorting #Heap_Priority_Queue #Counting
// #Divide_and_Conquer #Quickselect #Bucket_Sort #Data_Structure_II_Day_20_Heap_Priority_Queue
// #Big_O_Time_O(n*log(n))_Space_O(k) #2025_06_16_Time_7_ms_(75.70%)_Space_52.02_MB_(18.24%)
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] TopKFrequent(int[] nums, int k) {
if (k == nums.Length) {
return nums;
}
//1. build dictionary
Dictionary<int, int> dict = new Dictionary<int, int>();
for(int i=0; i < nums.Length; i++) {
if (!dict.ContainsKey(nums[i])) {
dict.Add(nums[i],0);
}
dict[nums[i]] +=1;
}
//2. build priority queue based on highest to lowest frequency
PriorityQueue<int, int> pq = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
foreach (var key in dict.Keys) {
pq.Enqueue(key, dict[key]);
}
// 3. return top k elements from Priority Queue
var result = new int[k];
for (var i = 0; i < k; i++) {
result[i] = pq.Dequeue();
}
return result;
}
}
}