MCPcopy
hub / github.com/qiyuangong/leetcode / topKFrequent

Method topKFrequent

java/692_Top_K_Frequent_Words.java:13–31  ·  view source on GitHub ↗
(String[] words, int k)

Source from the content-addressed store, hash-verified

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}

Callers

nothing calls this directly

Calls 4

putMethod · 0.45
getMethod · 0.45
addMethod · 0.45
reverseMethod · 0.45

Tested by

no test coverage detected