Skip to content

Commit f112596

Browse files
authored
Update Top K Frequent Words.java
1 parent 396d202 commit f112596

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

Medium/Top K Frequent Words.java

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
11
class Solution {
22
public List<String> topKFrequent(String[] words, int k) {
3-
Map<String, Integer> map = new HashMap<>();
3+
Map<String, Integer> wordFrequency = new HashMap<>();
4+
Map<Integer, Set<String>> frequencyToWord = new HashMap<>();
5+
int maxFrequency = 0;
46
for (String word : words) {
5-
map.put(word, map.getOrDefault(word, 0) + 1);
7+
if (!wordFrequency.containsKey(word)) {
8+
wordFrequency.put(word, 1);
9+
frequencyToWord.computeIfAbsent(1, j -> new HashSet<>()).add(word);
10+
} else {
11+
int oldFrequency = wordFrequency.get(word);
12+
int newFrequency = oldFrequency + 1;
13+
wordFrequency.put(word, newFrequency);
14+
frequencyToWord.get(oldFrequency).remove(word);
15+
frequencyToWord.computeIfAbsent(newFrequency, j -> new HashSet<>()).add(word);
16+
}
17+
maxFrequency = Math.max(maxFrequency, wordFrequency.get(word));
618
}
7-
PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>(){
8-
public int compare(String s1, String s2) {
9-
int c = map.get(s2) - map.get(s1);
10-
if (c != 0) {
11-
return c;
12-
}
13-
return s1.compareTo(s2);
19+
List<String> result = new ArrayList<>();
20+
for (int i = maxFrequency; i > 0 && result.size() < k; i--) {
21+
List<String> currFreqWords = new ArrayList<>(frequencyToWord.get(i));
22+
Collections.sort(currFreqWords);
23+
for (int j = 0; j < currFreqWords.size() && result.size() < k; j++) {
24+
result.add(currFreqWords.get(j));
1425
}
15-
});
16-
pq.addAll(map.keySet());
17-
List<String> ans = new ArrayList<>();
18-
while (!pq.isEmpty() && k-- > 0) {
19-
ans.add(pq.poll());
2026
}
21-
return ans;
27+
return result;
2228
}
2329
}

0 commit comments

Comments
 (0)