-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0347-Top-k-frequent-elements.cs
More file actions
45 lines (37 loc) · 1.15 KB
/
0347-Top-k-frequent-elements.cs
File metadata and controls
45 lines (37 loc) · 1.15 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
38
39
40
41
42
43
44
45
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0347.Top_k_frequent_elements
{
public class _0347_Top_k_frequent_elements
{
public int[] TopKFrequent(int[] nums, int k)
{
if (nums.Length == 1) return nums;
var dic = new Dictionary<int, int>();
var res = new int[k];
// record the number of occurrences of each element.
foreach (int num in nums)
if (!dic.TryAdd(num, 1))
dic[num]++;
int max = int.MinValue;
int i = 0;
// Iterate k times to find the number displayed the most times.
while (i < k)
{
foreach (KeyValuePair<int, int> pair in dic)
{
if (max == int.MinValue)
max = pair.Key;
else if (pair.Value > dic[max])
max = pair.Key;
}
res[i] = max;
dic.Remove(max);
max = int.MinValue;
i++;
}
return res;
}
}
}