LeetCode 146 LRU Cache (C++, Python)
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations:
Solution (C++)
Solution (Python)
It should support the following operations:
get
and set
.get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not
already present. When the cache reached its capacity, it should
invalidate the least recently used item before inserting a new item.Solution (C++)
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 | class LRUCache{ private: unordered_map<int, pair<int, list<int>::iterator>> cache; int room; list<int> accessOrder; public: LRUCache(int capacity):room(capacity) { } int get(int key) { auto it = cache.find(key); if (it == cache.end()) return -1; int ret = it->second.first; if (it->second.second != next(accessOrder.end(), - 1)) { accessOrder.splice(accessOrder.end(), accessOrder, it->second.second); } return ret; } void set(int key, int value) { auto it = cache.find(key); if (it == cache.end()) { if (room == 0) { auto it = cache[accessOrder.front()].second; cache.erase(accessOrder.front()); accessOrder.erase(it); } else { -- room; } accessOrder.push_back(key); cache.insert({key, {value, next(accessOrder.end(), -1)}}); } else { it->second.first = value; if (it->second.second != next(accessOrder.end(), - 1)) { accessOrder.splice(accessOrder.end(), accessOrder, it->second.second); } } } }; |
Solution (Python)
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 | from collections import OrderedDict class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.room = capacity self.ordmap = OrderedDict() # @return an integer def get(self, key): if key in self.ordmap: ret = self.ordmap[key] del self.ordmap[key] self.ordmap[key] = ret return ret else: return -1 # @param key, an integer # @param value, an integer # @return nothing def set(self, key, value): if key in self.ordmap: del self.ordmap[key] self.ordmap[key] = value else: if self.room: self.ordmap[key] = value self.room -= 1 else: self.ordmap.popitem(last=False) self.ordmap[key] = value |