-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0432_AllOne.cc
151 lines (137 loc) · 2.8 KB
/
Problem_0432_AllOne.cc
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <map>
#include <set>
#include <string>
#include "UnitTest.h"
using namespace std;
class AllOne
{
public:
AllOne()
{
// dummy node for coding easy
head = new Bucket("", 0);
tail = new Bucket("", INT32_MAX);
head->next = tail;
tail->last = head;
}
void inc(string key)
{
if (!map_.count(key))
{
if (head->next->cnt == 1)
{
map_[key] = head->next;
head->next->set_.emplace(key);
}
else
{
Bucket* newBucket = new Bucket(key, 1);
map_[key] = newBucket;
insert(head, newBucket);
}
}
else
{
Bucket* bucket = map_[key];
if (bucket->next->cnt == bucket->cnt + 1)
{
map_[key] = bucket->next;
bucket->next->set_.emplace(key);
}
else
{
Bucket* newBucket = new Bucket(key, bucket->cnt + 1);
map_[key] = newBucket;
insert(bucket, newBucket);
}
bucket->set_.erase(key);
if (bucket->set_.empty())
{
remove(bucket);
}
}
}
void dec(string key)
{
Bucket* bucket = map_[key];
if (bucket->cnt == 1)
{
map_.erase(key);
}
else
{
if (bucket->last->cnt == bucket->cnt - 1)
{
map_[key] = bucket->last;
bucket->last->set_.emplace(key);
}
else
{
Bucket* newBucket = new Bucket(key, bucket->cnt - 1);
map_[key] = newBucket;
insert(bucket->last, newBucket);
}
}
bucket->set_.erase(key);
if (bucket->set_.empty())
{
remove(bucket);
}
}
string getMaxKey() { return *tail->last->set_.begin(); }
string getMinKey() { return *head->next->set_.begin(); }
private:
class Bucket
{
public:
set<string> set_;
int cnt;
Bucket* last;
Bucket* next;
Bucket(const string& s, int c)
{
set_.emplace(s);
cnt = c;
}
};
void insert(Bucket* cur, Bucket* pos)
{
cur->next->last = pos;
pos->next = cur->next;
cur->next = pos;
pos->last = cur;
}
void remove(Bucket* cur)
{
cur->last->next = cur->next;
cur->next->last = cur->last;
}
Bucket* head;
Bucket* tail;
map<string, Bucket*> map_;
};
/**
* 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();
*/
void test()
{
AllOne allOne;
allOne.inc("hello");
allOne.inc("hello");
EXPECT_TRUE("hello" == allOne.getMaxKey()); // 返回 "hello"
EXPECT_TRUE("hello" == allOne.getMinKey()); // 返回 "hello"
allOne.inc("leet");
EXPECT_TRUE("hello" == allOne.getMaxKey()); // 返回 "hello"
EXPECT_TRUE("leet" == allOne.getMinKey()); // 返回 "leet"
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}