- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 48 lines of C++ from the credited upstream file 146-2.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 int key;3 int value;4};5 6class LRUCache {7 public:8 LRUCache(int capacity) : capacity(capacity) {}9 10 int get(int key) {11 const auto it = keyToIterator.find(key);12 if (it == keyToIterator.cend())13 return -1;14 15 const auto& listIt = it->second;16 17 cache.splice(cache.begin(), cache, listIt);18 return listIt->value;19 }20 21 void put(int key, int value) {22 23 if (const auto it = keyToIterator.find(key); it != keyToIterator.cend()) {24 const auto& listIt = it->second;25 26 cache.splice(cache.begin(), cache, listIt);27 listIt->value = value;28 return;29 }30 31 32 if (cache.size() == capacity) {33 const Node& lastNode = cache.back();34 35 keyToIterator.erase(lastNode.key);36 cache.pop_back();37 }38 39 cache.emplace_front(key, value);40 keyToIterator[key] = cache.begin();41 }42 43 private:44 const int capacity;45 list<Node> cache;46 unordered_map<int, list<Node>::iterator> keyToIterator;47};48