class Solution { /*public List topKFrequent(String[] words, int k) { Map count = new HashMap(); for (String word: words) { count.put(word, count.getOrDefault(word, 0) + 1); } List candidates = new ArrayList(count.keySet()); Collections.sort(candidates, (w1, w2) -> count.get(w1).equals(count.get(w2)) ? w1.compareTo(w2) : count.get(w2) - count.get(w1)); return candidates.subList(0, k); }*/ public List topKFrequent(String[] words, int k) { Map count = new HashMap(); for (String word: words) { count.put(word, count.getOrDefault(word, 0) + 1); } PriorityQueue heap = new PriorityQueue( (w1, w2) -> count.get(w1).equals(count.get(w2)) ? w2.compareTo(w1) : count.get(w1) - count.get(w2) ); for (String word: count.keySet()) { heap.offer(word); if (heap.size() > k) heap.poll(); } List ans = new ArrayList(); while (!heap.isEmpty()) ans.add(heap.poll()); Collections.reverse(ans); return ans; } }