-
Notifications
You must be signed in to change notification settings - Fork 0
/
692. Top K Frequent Words.java
49 lines (49 loc) · 1.62 KB
/
692. Top K Frequent Words.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
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> list =new ArrayList<>();
Map<String,Integer> map=new HashMap<>();
Map<Integer,TreeSet<String>> bucket=new TreeMap<>(Collections.reverseOrder());
for(String s:words)
{
if(map.containsKey(s))
{
int count=map.get(s)+1;
map.put(s,count);
}
else
{
map.put(s,1);
}
}
for(Map.Entry<String,Integer> ele:map.entrySet())
{
TreeSet<String> set;
if(bucket.containsKey(ele.getValue()))
{
set=bucket.get(ele.getValue());
set.add(ele.getKey());
bucket.put(ele.getValue(),set);
}
else
{
set=new TreeSet<>();
set.add(ele.getKey());
bucket.put(ele.getValue(),set);
}
}
for(Map.Entry<Integer,TreeSet<String>> ele:bucket.entrySet())
{
if(k==0)
{
return list;
}
Iterator<String> itr = ele.getValue().iterator();
while (k!=0 && itr.hasNext()) {
list.add(itr.next());
k--;
}
}
return list;
}
}