Leetcode 692. Top K Frequent Words
Solution to Top K Frequent Words problem.
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
for(String word : words) {
int curFreq = freqMap.getOrDefault(word, 0);
freqMap.put(word, ++curFreq);
}
PriorityQueue<String> minHeap = new PriorityQueue<String>(
(s1, s2) -> {
// Do s2.compareTo(s1) to place s2 ahead of s1
// This will ensure proper Lexicographic ordering of output
// when we call Collection.reverse at the last step.
if (freqMap.get(s1) == freqMap.get(s2)) return s2.compareTo(s1);
return freqMap.get(s1) - freqMap.get(s2);
});
for(Map.Entry<String, Integer> e : freqMap.entrySet()) {
minHeap.add(e.getKey());
if (minHeap.size() > k) {
System.out.println("Evicting "+ minHeap.poll());
}
}
List<String> r = new ArrayList<String>();
System.out.println("Heap contains ");
while(minHeap.size() > 0) {
String e = minHeap.poll();
System.out.println(e);
r.add(e);
}
Collections.reverse(r);
return r;
}
}
Checkout this nice solution with explanation in leetcode community.