-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathAllOoneDataStructure.java
More file actions
109 lines (103 loc) · 2.66 KB
/
AllOoneDataStructure.java
File metadata and controls
109 lines (103 loc) · 2.66 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
109
class Node {
Node next;
Node prev;
int freq;
HashSet<String> keys;
Node(int f){
next = null;
prev = null;
freq = f;
keys = new HashSet<>();
}
}
class AllOne {
HashMap<String, Node> map;
Node head;
Node tail;
public AllOne() {
head = new Node(0);
tail = new Node(0);
map = new HashMap<>();
head.next = tail;
tail.prev = head;
}
public void inc(String key) {
Node cur = head;
int newFreq = 1;
if(map.containsKey(key)){
cur = map.get(key);
newFreq = cur.freq + 1;
cur.keys.remove(key);
}
if(cur.next.freq == newFreq){
cur.next.keys.add(key);
}else{ // insert a node with newFreq
Node node = new Node(newFreq);
node.keys.add(key);
Node nextNode = cur.next;
node.next = nextNode;
nextNode.prev = node;
cur.next = node;
node.prev = cur;
}
map.put(key, cur.next);
if(cur.keys.size()==0 && cur!=head){
removeNode(cur);
}
}
public void dec(String key) {
Node cur = map.get(key);
int newFreq = cur.freq - 1;
cur.keys.remove(key);
if(newFreq == 0){
if(cur.keys.size()==0){
removeNode(cur);
}
map.remove(key);
return;
}
if(cur.prev.freq == newFreq){
cur.prev.keys.add(key);
}else{ // insert a node with newFreq
Node node = new Node(newFreq);
node.keys.add(key);
Node prevNode = cur.prev;
node.prev = prevNode;
prevNode.next = node;
node.next = cur;
cur.prev = node;
}
map.put(key, cur.prev);
if(cur.keys.size()==0 && cur!=head){
removeNode(cur);
}
}
public String getMaxKey() {
if(tail.prev == head){
return "";
}
return tail.prev.keys.iterator().next();
}
public String getMinKey() {
if(head.next == tail){
return "";
}
return head.next.keys.iterator().next();
}
private void removeNode(Node cur){
Node nextNode = cur.next;
Node prevNode = cur.prev;
prevNode.next = nextNode;
nextNode.prev = prevNode;
cur.next = null;
cur.prev = null;
}
}
/**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* String param_3 = obj.getMaxKey();
* String param_4 = obj.getMinKey();
*/