public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
PriorityQueue<WordInfo> minHeap = new PriorityQueue<>();
for (String key : map.keySet()) {
minHeap.add(new WordInfo(key, map.get(key)));
if (minHeap.size() > k) {
while (!minHeap.isEmpty()) {
res.add(0, minHeap.remove().word);
class WordInfo implements Comparable<WordInfo> {
public WordInfo(String word, int freq) {
public int compareTo(WordInfo that) {
return this.freq == that.freq ? that.word.compareTo(word) : this.freq - that.freq;