Problem
题目大意:设计一种数据结构,支持inc/dec/getmaxkey/getminkey操作,必须都在O(1)时间内完成。
https://leetcode.com/problems/all-oone-data-structure/description/
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.
Solution
Time complexity: O(1)
Space complexity: O(n), n = # of unique keys
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 |
// Author: Huahua // Running time: 32 ms class AllOne { 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) { auto it = m_.find(key); if (it == m_.end()) { if (l_.empty() || l_.front().value != 1) l_.push_front({1, {key}}); else l_.front().keys.insert(key); m_[key] = l_.begin(); return; } auto lit = it->second; auto nit = next(lit); if (nit == l_.end() || nit->value != lit->value + 1) nit = l_.insert(nit, {lit->value + 1, {}}); nit->keys.insert(key); m_[key] = nit; remove(lit, key); } /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ void dec(string key) { auto it = m_.find(key); if (it == m_.end()) return; auto lit = it->second; if (lit->value > 1) { auto pit = prev(lit); if (lit == l_.begin() || pit->value != lit->value - 1) pit = l_.insert(lit, {lit->value - 1, {}}); pit->keys.insert(key); m_[key] = pit; } else { // value == 1, remove from the data structure m_.erase(key); } remove(lit, key); } /** Returns one of the keys with maximal value. */ string getMaxKey() { return l_.empty() ? "" : *l_.back().keys.cbegin(); } /** Returns one of the keys with Minimal value. */ string getMinKey() { return l_.empty() ? "" : *l_.front().keys.cbegin(); } private: struct Node { int value; unordered_set<string> keys; }; list<Node> l_; unordered_map<string, list<Node>::iterator> m_; // Remove from old node. void remove(list<Node>::iterator it, const string& key) { it->keys.erase(key); if (it->keys.empty()) l_.erase(it); } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment