-
Notifications
You must be signed in to change notification settings - Fork 2
/
TopKFrequentWords.java
65 lines (58 loc) · 1.64 KB
/
TopKFrequentWords.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.algorithm.playground.leetcode.problems.lc600.lc690.lc692;
import java.util.*;
/**
* https://leetcode.com/problems/top-k-frequent-words/description/
*/
@SuppressWarnings("Duplicates")
public class TopKFrequentWords {
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}
//noinspection unchecked
ArrayList<String>[] buckets = new ArrayList[words.length];
for (String key : counts.keySet()) {
Integer count = counts.get(key);
if (buckets[count] == null) {
buckets[count] = new ArrayList<>();
}
buckets[count].add(key);
}
List<String> result = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) {
if (buckets[i] != null) {
buckets[i].sort(String::compareTo);
result.addAll(buckets[i]);
}
}
return result.subList(0, k);
}
}
class PriorityQueueSolution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}
Queue<String> queue = new PriorityQueue<>((s1, s2) -> {
if (counts.get(s1).equals(counts.get(s2))) {
return s2.compareTo(s1);
}
return counts.get(s1) - counts.get(s2);
});
for (String key : counts.keySet()) {
queue.offer(key);
if (queue.size() > k) {
queue.poll();
}
}
List<String> result = new ArrayList<>();
while (!queue.isEmpty()) {
result.add(0, queue.poll());
}
return result;
}
}
}