# 0692. Top K Frequent Words ###### tags: `Leetcode` `Medium` `Bloomberg` `Top K Elements` ## 思路 和[0374. Top K Frequent Elements](https://hackmd.io/Jeme3R_LQ22DGczpi9TQ9g)有点类似,但是由于如果出现的频率一样,还要再根据字母排序,所以quicksort会有点麻烦 要注意的是comparator的写法,到底是正着排还是反着排,很容易搞错 frequency是取大的,在frequency一样的情况下,取比较小的字符串 ## Code ```java= class Solution { public List<String> topKFrequent(String[] words, int k) { Map<String, Integer> count = new HashMap<>(); for(String word:words){ count.put(word,count.getOrDefault(word,0)+1); } Queue<String> pq = new PriorityQueue<>(new Comparator<>(){ public int compare(String a, String b){ if(count.get(a)!=count.get(b)){ return count.get(a)-count.get(b); } else{ return b.compareTo(a); } } }); for(String word:count.keySet()){ pq.add(word); if(pq.size()>k){ pq.poll(); } } List<String> ans = new ArrayList<>(); while(!pq.isEmpty()){ ans.add(0,pq.poll()); } return ans; } } ```