-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAllOne.cpp
More file actions
66 lines (54 loc) · 2 KB
/
AllOne.cpp
File metadata and controls
66 lines (54 loc) · 2 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
class AllOne {
public:
void inc(string key) {
// If the key doesn't exist, insert it with value 0.
if (!bucketOfKey.count(key))
bucketOfKey[key] = buckets.insert(buckets.begin(), {0, {key}});
// Insert the key in next bucket and update the lookup.
auto next = bucketOfKey[key], bucket = next++;
if (next == buckets.end() || next->value > bucket->value + 1)
next = buckets.insert(next, {bucket->value + 1, {}});
next->keys.insert(key);
bucketOfKey[key] = next;
// Remove the key from its old bucket.
bucket->keys.erase(key);
if (bucket->keys.empty())
buckets.erase(bucket);
}
void dec(string key) {
// If the key doesn't exist, just leave.
if (!bucketOfKey.count(key))
return;
// Maybe insert the key in previous bucket and update the lookup.
auto prev = bucketOfKey[key], bucket = prev--;
bucketOfKey.erase(key);
if (bucket->value > 1) {
if (bucket == buckets.begin() || prev->value < bucket->value - 1)
prev = buckets.insert(bucket, {bucket->value - 1, {}});
prev->keys.insert(key);
bucketOfKey[key] = prev;
}
// Remove the key from its old bucket.
bucket->keys.erase(key);
if (bucket->keys.empty())
buckets.erase(bucket);
}
string getMaxKey() {
return buckets.empty() ? "" : *(buckets.rbegin()->keys.begin());
}
string getMinKey() {
return buckets.empty() ? "" : *(buckets.begin()->keys.begin());
}
private:
struct Bucket { int value; unordered_set<string> keys; };
list<Bucket> buckets;
unordered_map<string, list<Bucket>::iterator> bucketOfKey;
};
/**
* 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();
*/