-
Notifications
You must be signed in to change notification settings - Fork 0
/
AllOoneDS.cpp
62 lines (49 loc) · 1.87 KB
/
AllOoneDS.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
#include<bits/stdc++.h>
using namespace std;
// * Problem Link: https://leetcode.com/problems/all-oone-data-structure/description/?envType=daily-question&envId=2024-09-29
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;
};