forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall-oone-data-structure_1_AC.cpp
109 lines (97 loc) · 2.72 KB
/
all-oone-data-structure_1_AC.cpp
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
// I don't wanna lay my eyes on this code for one more second.
// Too complicated, too sloppy, although the idea is simple.
// std::list is a doubly linked list, so why bother writing your own?
#include <list>
#include <string>
#include <unordered_map>
#include <unordered_set>
using std::list;
using std::string;
using std::unordered_map;
using std::unordered_set;
typedef unordered_set<string> USS;
class AllOne {
public:
/** Initialize your data structure here. */
AllOne() {}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
void inc(string key) {
int val = m1.find(key) != m1.end() ? m1[key] : 0;
++m1[key];
list<USS>::iterator it1, it2;
it1 = val > 0 ? m2[val] : a.begin();
if (m2.find(val + 1) == m2.end()) {
it2 = a.insert(val > 0 ? next(it1) : a.begin(), USS());
m2[val + 1] = it2;
} else {
it2 = m2[val + 1];
}
it2->insert(key);
if (val > 0) {
it1->erase(key);
if (it1->size() == 0) {
a.erase(it1);
m2.erase(val);
}
}
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key) {
int val = m1.find(key) != m1.end() ? m1[key] : 0;
if (val == 0) {
return;
}
if (val > 1) {
--m1[key];
} else {
m1.erase(key);
}
list<USS>::iterator it1, it2;
it1 = m2[val];
if (val > 1) {
if (m2.find(val - 1) == m2.end()) {
it2 = a.insert(it1, USS());
m2[val - 1] = it2;
} else {
it2 = m2[val - 1];
}
it2->insert(key);
}
it1->erase(key);
if (it1->size() == 0) {
a.erase(it1);
m2.erase(val);
}
}
/** Returns one of the keys with maximal value. */
string getMaxKey() {
if (a.size() == 0) {
return "";
}
return *(a.back().begin());
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
if (a.size() == 0) {
return "";
}
return *(a.front().begin());
}
~AllOne() {
a.clear();
m1.clear();
m2.clear();
}
private:
list<USS> a;
unordered_map<string, int> m1;
unordered_map<int, list<USS>::iterator> m2;
};
/**
* 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();
*/