| 11 | return candidates.subList(0, k); |
| 12 | }*/ |
| 13 | public List<String> topKFrequent(String[] words, int k) { |
| 14 | Map<String, Integer> count = new HashMap(); |
| 15 | for (String word: words) { |
| 16 | count.put(word, count.getOrDefault(word, 0) + 1); |
| 17 | } |
| 18 | PriorityQueue<String> heap = new PriorityQueue<String>( |
| 19 | (w1, w2) -> count.get(w1).equals(count.get(w2)) ? |
| 20 | w2.compareTo(w1) : count.get(w1) - count.get(w2) ); |
| 21 | |
| 22 | for (String word: count.keySet()) { |
| 23 | heap.offer(word); |
| 24 | if (heap.size() > k) heap.poll(); |
| 25 | } |
| 26 | |
| 27 | List<String> ans = new ArrayList(); |
| 28 | while (!heap.isEmpty()) ans.add(heap.poll()); |
| 29 | Collections.reverse(ans); |
| 30 | return ans; |
| 31 | } |
| 32 | } |