-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathAllOneDataStructure.java
58 lines (51 loc) · 1.51 KB
/
AllOneDataStructure.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
50
51
52
53
54
55
56
57
58
/*https://leetcode.com/problems/all-oone-data-structure/*/
class AllOne {
Map<String, Integer> map;
TreeMap<Integer, Set<String>> maxMap;
public AllOne() {
map = new HashMap<>();
maxMap = new TreeMap<>();
}
public void inc(String key) {
int val = map.getOrDefault(key, 0);
Set<String> s = maxMap.getOrDefault(val, new HashSet<>());
s.remove(key);
if (s.isEmpty()) {
maxMap.remove(val);
} else {
maxMap.put(val, s);
}
val++;
Set<String> s1 = maxMap.getOrDefault(val, new HashSet<>());
s1.add(key);
maxMap.put(val, s1);
map.put(key, val);
}
public void dec(String key) {
int val = map.getOrDefault(key, 0);
Set<String> s = maxMap.getOrDefault(val, new HashSet<>());
s.remove(key);
if (s.isEmpty()) {
maxMap.remove(val);
} else {
maxMap.put(val, s);
}
val--;
if (val < 1) {
map.remove(key);
} else {
map.put(key, val);
Set<String> s1 = maxMap.getOrDefault(val, new HashSet<>());
s1.add(key);
maxMap.put(val, s1);
}
}
public String getMaxKey() {
if (maxMap.isEmpty()) return "";
return maxMap.get(maxMap.lastKey()).iterator().next();
}
public String getMinKey() {
if (maxMap.isEmpty()) return "";
return maxMap.get(maxMap.firstKey()).iterator().next();
}
}