146. LRU Cache
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.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ ); 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 4
C++:
1 class LRUCache { 2 public: 3 struct CacheNode{ 4 int key; 5 int value; 6 CacheNode(int k,int v):key(k),value(v){} 7 }; 8 9 LRUCache(int capacity) { 10 this->capacity = capacity; 11 } 12 13 int get(int key) { 14 if(cachemap.find(key)==cachemap.end()) 15 return -1; 16 //将当前访问的节点移动到列表头部,并且更新map中该节点的地址(索引) 17 cachelist.splice(cachelist.begin(), cachelist, cachemap[key]); 18 cachemap[key] = cachelist.begin(); 19 return cachemap[key]->value; 20 } 21 22 void put(int key, int value) { 23 if(cachemap.find(key)!=cachemap.end()){ 24 //更新节点的值,把当前访问的节点移到列表头部,并且更新map中该节点的地址 25 cachemap[key]->value = value; 26 cachelist.splice(cachelist.begin(), cachelist, cachemap[key]); 27 cachemap[key] = cachelist.begin(); 28 } 29 else{ 30 if(cachelist.size()==capacity){//删除尾部最少访问的 31 cachemap.erase(cachelist.back().key); 32 cachelist.pop_back(); 33 } 34 cachelist.push_front(CacheNode(key, value)); 35 cachemap[key] = cachelist.begin(); 36 } 37 } 38 private: 39 //list用于存储当前容量的内存页,map为便于O(1)内查询到list中的某个页 40 list<CacheNode> cachelist; 41 unordered_map<int,list<CacheNode>::iterator> cachemap; 42 int capacity; 43 }; 44 45 /** 46 * Your LRUCache object will be instantiated and called as such: 47 * LRUCache obj = new LRUCache(capacity); 48 * int param_1 = obj.get(key); 49 * obj.put(key,value); 50 */