forked from algorithm001/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_692_113.java
More file actions
36 lines (29 loc) · 988 Bytes
/
Copy pathleetcode_692_113.java
File metadata and controls
36 lines (29 loc) · 988 Bytes
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
class Solution {
public List<String> topKFrequent(String[] words, int k) {
if (words == null) return null;
Comparator<Map.Entry> valueComparator = new Comparator<Map.Entry>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
return (Integer)o2.getValue() - (Integer)o1.getValue();
}
};
Map<String, Integer> map = new TreeMap();
for(String s : words) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + 1);
} else {
map.put(s, 1);
}
}
List<Map.Entry<String, Integer>> l = new ArrayList(map.entrySet());
Collections.sort(l, valueComparator);
int c = 0;
List<String> list = new ArrayList();
for (Map.Entry<String, Integer> entry : l) {
list.add(entry.getKey());
++c;
if (c >= k) break;
}
return list;
}
}