-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAllOne.java
More file actions
72 lines (64 loc) · 1.62 KB
/
Copy pathAllOne.java
File metadata and controls
72 lines (64 loc) · 1.62 KB
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
66
67
68
69
70
71
72
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class AllOne
{
private Map<String, Integer> map;
private PriorityQueue<String> maxQueue;
private PriorityQueue<String> minQueue;
public AllOne()
{
map = new HashMap<String, Integer>();
maxQueue = new PriorityQueue<>(new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return map.get(o1) - map.get(o2);
}
});
minQueue = new PriorityQueue<>(new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return map.get(o2) - map.get(o1);
}
});
}
public void inc(String key)
{
map.put(key, map.getOrDefault(key, 0) + 1);
maxQueue.remove(key);
minQueue.remove(key);
maxQueue.add(key);
minQueue.add(key);
}
public void dec(String key)
{
if (map.containsKey(key))
{
maxQueue.remove(key);
minQueue.remove(key);
if (map.get(key) == 1)
{
map.remove(key);
}
else
{
map.put(key, map.get(key) - 1);
maxQueue.add(key);
minQueue.add(key);
}
}
}
public String getMaxKey()
{
return maxQueue.isEmpty() ? "" : maxQueue.peek();
}
public String getMinKey()
{
return minQueue.isEmpty() ? "" : minQueue.peek();
}
}