Implement a data structure supporting the following operations:
- Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
- Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
- GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string
""
. - GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string
""
.
Challenge: Perform all these in O(1) time complexity.
参考资料:here。
class AllOne {
private:
struct Bucket {
int val;
unordered_set<string> keys;
};
list<Bucket> buckets;
unordered_map<string, list<Bucket>::iterator> hash;
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) {
if (!hash.count(key)) {
buckets.insert(buckets.begin(), { 0,{key} });
hash[key] = buckets.begin();
}
auto next = hash[key], bucket = next++;
if (next == buckets.end() || next->val > bucket->val + 1) {
next = buckets.insert(next, { bucket->val + 1,{} });
}
next->keys.insert(key);
hash[key] = next;
bucket->keys.erase(key);
if (bucket->keys.empty()) buckets.erase(bucket);
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key) {
if (!hash.count(key)) return;
auto prev = hash[key], bucket = prev--;
hash.erase(key);
if (bucket->val > 1) {
if (bucket == buckets.begin() || prev->val < bucket->val - 1) {
prev = buckets.insert(bucket, { bucket->val - 1,{} });
}
prev->keys.insert(key);
hash[key] = prev;
}
bucket->keys.erase(key);
if (bucket->keys.empty()) buckets.erase(bucket);
}
/** Returns one of the keys with maximal value. */
string getMaxKey() {
return buckets.empty() ? "" : *(buckets.rbegin()->keys.begin());
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
return buckets.empty() ? "" : *(buckets.begin()->keys.begin());
}
};