forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
26 lines (26 loc) · 858 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> counter = new HashMap<>();
for (String word : words) {
counter.put(word, counter.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> minHeap = new PriorityQueue<>((a, b) -> {
if (counter.get(a).equals(counter.get(b))) {
return b.compareTo(a);
}
return counter.get(a) - counter.get(b);
});
for (String word : counter.keySet()) {
minHeap.offer(word);
if (minHeap.size() > k) {
minHeap.poll();
}
}
List<String> res = new ArrayList<>();
while (!minHeap.isEmpty()) {
res.add(minHeap.poll());
}
Collections.reverse(res);
return res;
}
}