-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAll_432.java
More file actions
99 lines (80 loc) · 2.67 KB
/
All_432.java
File metadata and controls
99 lines (80 loc) · 2.67 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class All_432 {
Map<String, Integer> count;
Map<Integer, Bucket> buckets;
Bucket head, tail;
class Bucket {
int val;
Set<String> keys;
Bucket prev, next;
Bucket() {}
Bucket(int _val) {
val = _val;
keys = new HashSet<>();
}
}
/** Initialize your data structure here. */
public All_432() {
count = new HashMap<>();
buckets = new HashMap<>();
head = new Bucket();
tail = new Bucket();
head.next = tail;
tail.prev = head;
}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
public void inc(String key) {
int val = updateCountMap(key, 1);
updateBucketList(key, val, 1);
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
public void dec(String key) {
if (!count.containsKey(key)) return;
int val = updateCountMap(key, -1);
updateBucketList(key, val, -1);
}
private void updateBucketList(String key, int val, int incr) {
Bucket curBuc = buckets.getOrDefault(val, head);
val += incr;
if (buckets.containsKey(val)) buckets.get(val).keys.add(key);
else if (incr > 0) addBefore(curBuc.next, key, val);
else if (val > 0) addBefore(curBuc, key, val);
removeFromBucket(curBuc, key);
}
private int updateCountMap(String key, int incr) {
int val = count.getOrDefault(key, 0);
count.remove(key);
if (val + incr > 0) count.put(key, val + incr);
return val;
}
private void addBefore(Bucket curBuc, String key, int val) {
Bucket newBuc = new Bucket(val);
newBuc.val = val;
newBuc.keys.add(key);
newBuc.next = curBuc;
newBuc.prev = curBuc.prev;
newBuc.next.prev = newBuc;
newBuc.prev.next = newBuc;
buckets.put(val, newBuc);
}
private void removeFromBucket(Bucket curBuc, String key) {
if (curBuc.keys == null) return;
curBuc.keys.remove(key);
if (curBuc.keys.isEmpty()) {
curBuc.prev.next = curBuc.next;
curBuc.next.prev = curBuc.prev;
buckets.remove(curBuc.val);
}
}
/** Returns one of the keys with maximal value. */
public String getMaxKey() {
return tail.prev == head ? "" : tail.prev.keys.iterator().next();
}
/** Returns one of the keys with Minimal value. */
public String getMinKey() {
return head.next == tail ? "" : head.next.keys.iterator().next();
}
}