-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path692TopKFrequentWords.cs
More file actions
62 lines (51 loc) · 1.84 KB
/
692TopKFrequentWords.cs
File metadata and controls
62 lines (51 loc) · 1.84 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeForecs
{
class _692TopKFrequentWords
{
public IList<string> TopKFrequent(string[] nums, int k)
{
IDictionary<string, int> frequencyDictionary = new Dictionary<string, int>();
int maximumFrequency = 0, minimumFrequency = Int32.MaxValue;
foreach(string i in nums)
{
if (frequencyDictionary.ContainsKey(i))
{
frequencyDictionary[i] += 1;
}
else
{
frequencyDictionary.Add(i, 1);
}
maximumFrequency = Math.Max(maximumFrequency, frequencyDictionary[i]);
minimumFrequency = Math.Min(minimumFrequency, frequencyDictionary[i]);
}
List<string>[] bucketSortArray = new List<string>[maximumFrequency - minimumFrequency + 1];
for (int i = 0; i < bucketSortArray.Length; i++)
{
bucketSortArray[i] = new List<string>();
}
foreach (var obj in frequencyDictionary)
{
bucketSortArray[obj.Value - minimumFrequency].Add(obj.Key);
}
foreach (var obj in frequencyDictionary)
{
bucketSortArray[obj.Value - minimumFrequency].Sort();
}
IList<string> topKElements = new List<string>();
for (int i = bucketSortArray.Length - 1; i >= 0 && topKElements.Count < k; i--)
{
int j = 0;
while (j < bucketSortArray[i].Count && topKElements.Count < k)
{
topKElements.Add(bucketSortArray[i][j]);
j++;
}
}
return topKElements;
}
}
}