LeetCode432. All O`one Data Structure

Implement a data structure supporting the following operations:

 

  1. 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.
  2. 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.
  3. GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".
  4. 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());
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值