-
Notifications
You must be signed in to change notification settings - Fork 0
/
FrequentWords.java
40 lines (31 loc) · 1.15 KB
/
FrequentWords.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
package com.company.LeetCode;
import java.util.*;
import java.util.Map.*;
// https://leetcode.com/problems/top-k-frequent-words/
public class FrequentWords {
public static void main(String[] args) {
String[] words = {"the","day","is","sunny","the","the","the","sunny","is","is"};
System.out.println(topKFrequent(words, 4));
}
static public List<String> topKFrequent(String[] words, int k) {
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for (String s : words) {
if(!map.containsKey(s)){
map.put(s, 1);
}
else {
map.put(s, map.get(s) + 1);
}
}
List<Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
// System.out.println(map);
// System.out.println(list);
List<String> ans = new ArrayList<>();
for (int i = 0; i < k; i++) {
ans.add(list.get(i).getKey());
}
// System.out.println(ans);
return ans;
}
}