Repository navigation
Expand file tree
/
Copy pathCode07_AllO1.java
More file actions
108 lines (91 loc) · 2.15 KB
/
Copy pathCode07_AllO1.java
File metadata and controls
108 lines (91 loc) · 2.15 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
100
101
102
103
104
105
106
107
108
package class035;
import java.util.HashMap;
import java.util.HashSet;
// 全O(1)的数据结构
public class Code07_AllO1 {
// 测试链接 : https://leetcode.cn/problems/all-oone-data-structure/
class AllOne {
class Bucket {
public HashSet<String> set;
public int cnt;
public Bucket last;
public Bucket next;
public Bucket(String s, int c) {
set = new HashSet<>();
set.add(s);
cnt = c;
}
}
private void insert(Bucket cur, Bucket pos) {
cur.next.last = pos;
pos.next = cur.next;
cur.next = pos;
pos.last = cur;
}
private void remove(Bucket cur) {
cur.last.next = cur.next;
cur.next.last = cur.last;
}
Bucket head;
Bucket tail;
HashMap<String, Bucket> map;
public AllOne() {
head = new Bucket("", 0);
tail = new Bucket("", Integer.MAX_VALUE);
head.next = tail;
tail.last = head;
map = new HashMap<>();
}
public void inc(String key) {
if (!map.containsKey(key)) {
if (head.next.cnt == 1) {
map.put(key, head.next);
head.next.set.add(key);
} else {
Bucket newBucket = new Bucket(key, 1);
map.put(key, newBucket);
insert(head, newBucket);
}
} else {
Bucket bucket = map.get(key);
if (bucket.next.cnt == bucket.cnt + 1) {
map.put(key, bucket.next);
bucket.next.set.add(key);
} else {
Bucket newBucket = new Bucket(key, bucket.cnt + 1);
map.put(key, newBucket);
insert(bucket, newBucket);
}
bucket.set.remove(key);
if (bucket.set.isEmpty()) {
remove(bucket);
}
}
}
public void dec(String key) {
Bucket bucket = map.get(key);
if (bucket.cnt == 1) {
map.remove(key);
} else {
if (bucket.last.cnt == bucket.cnt - 1) {
map.put(key, bucket.last);
bucket.last.set.add(key);
} else {
Bucket newBucket = new Bucket(key, bucket.cnt - 1);
map.put(key, newBucket);
insert(bucket.last, newBucket);
}
}
bucket.set.remove(key);
if (bucket.set.isEmpty()) {
remove(bucket);
}
}
public String getMaxKey() {
return tail.last.set.iterator().next();
}
public String getMinKey() {
return head.next.set.iterator().next();
}
}
}