Created
October 7, 2021 01:19
-
-
Save Kavignon/ced990c8b1469ad6172da42ff9916e36 to your computer and use it in GitHub Desktop.
Implementation for the LeetCode problem 'Top K frequent words' solved with an hash table and min-heap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution | |
{ | |
public IList<string> TopKFrequent(string[] words, int k) { | |
var output = new string[k]; | |
if (words == null || words.Length == 0) | |
{ | |
return output; | |
} | |
var wordFrequencyMap = new Dictionary<string, int>(); | |
foreach (string word in words) | |
{ | |
if (wordFrequencyMap.ContainsKey(word)) | |
{ | |
wordFrequencyMap[word]++; | |
} | |
else | |
{ | |
wordFrequencyMap.Add(word, 1); | |
} | |
} | |
var heap = new SortedSet<(int frequency, string word)>(new WordFrequencyComparer()); | |
foreach (var pair in wordFrequencyMap) | |
{ | |
heap.Add((pair.Value * -1, pair.Key)); | |
} | |
int idx = 0; | |
foreach (var pair in heap) | |
{ | |
if (idx == k) | |
{ | |
break; | |
} | |
output[idx] = pair.word; | |
idx++; | |
} | |
return output; | |
} | |
} | |
public class WordFrequencyComparer : IComparer<(int frequency, string word)> | |
{ | |
public int Compare((int frequency, string word) firstWordFrequency, (int frequency, string word) secondWordFrequency) | |
{ | |
if (firstWordFrequency.frequency == secondWordFrequency.frequency) | |
{ | |
return firstWordFrequency.word.CompareTo(secondWordFrequency.word); | |
} | |
return firstWordFrequency.frequency - secondWordFrequency.frequency; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment