Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.前端
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.code
Follow up:
Could you do both operations in O(1) time complexity?索引
Example:ci
LRUCache cache = new LRUCache( 2 / capacity / );get
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4hash
由於要求是O(1)的複雜度,所以必需要用hash來索引。要求LRU規則的淘汰,所以創建一個鏈表,每次對key產生訪問以後,就將此kv移動到最前端。容器不夠時,從末端進行淘汰。it
class LRUCache { private: typedef std::pair<int, int> Node; typedef std::list<Node> Cont; typedef Cont::iterator Iter; typedef std::unordered_map<int, Iter> Idx; Cont _cont; Idx _idx; int _cap; int _num; public: LRUCache(int capacity) : _cap(capacity), _num(0) { } int get(int key) { auto it = _idx.find(key); if (it == _idx.end()) { return -1; } Node n = *(it->second); _cont.erase(it->second); _cont.push_front(n); _idx[key] = _cont.begin(); return n.second; } void put(int key, int value) { auto it = _idx.find(key); if (it != _idx.end()) { _cont.erase(it->second); _idx.erase(it); _num--; } if (_num >= _cap) { Node b = _cont.back(); _cont.pop_back(); _num -= _idx.erase(b.first); } Node n(key, value); _cont.push_front(n); _idx[key] = _cont.begin(); _num++; return ; } }; /** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */