-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAll O`one Data Structure
75 lines (67 loc) Β· 1.93 KB
/
All O`one Data Structure
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
#include <unordered_map>
#include <list>
#include <string>
class AllOne {
private:
struct Node {
int count;
std::unordered_set<std::string> keys;
Node(int c) : count(c) {}
};
std::list<Node> nodes;
std::unordered_map<std::string, std::list<Node>::iterator> keyMap;
public:
AllOne() {}
void inc(string key) {
if (keyMap.find(key) == keyMap.end()) {
if (nodes.empty() || nodes.front().count != 1) {
nodes.push_front(Node(1));
}
nodes.front().keys.insert(key);
keyMap[key] = nodes.begin();
} else {
auto it = keyMap[key];
auto nxt = std::next(it);
if (nxt == nodes.end() || nxt->count != it->count + 1) {
nxt = nodes.insert(nxt, Node(it->count + 1));
}
nxt->keys.insert(key);
keyMap[key] = nxt;
it->keys.erase(key);
if (it->keys.empty()) {
nodes.erase(it);
}
}
}
void dec(string key) {
auto it = keyMap[key];
if (it->count > 1) {
auto prev = std::prev(it);
if (it == nodes.begin() || prev->count != it->count - 1) {
prev = nodes.insert(it, Node(it->count - 1));
}
prev->keys.insert(key);
keyMap[key] = prev;
} else {
keyMap.erase(key);
}
it->keys.erase(key);
if (it->keys.empty()) {
nodes.erase(it);
}
}
string getMaxKey() {
return nodes.empty() ? "" : *nodes.back().keys.begin();
}
string getMinKey() {
return nodes.empty() ? "" : *nodes.front().keys.begin();
}
};
/**
* 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();
*/