Design and implement a data structure for Least Recently Used (LRU) cache. 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.
struct CacheNode { int key; int value; CacheNode(int k,int v):key(k),value(v){} }; class LRUCache{ public: LRUCache(int capacity) { size=capacity; } int get(int key) { if(lmap.count(key)) { auto iter=lmap[key]; lis.splice(lis.begin(),lis,iter); lmap[key]=lis.begin(); return lis.begin()->value; } else return -1; } void set(int key, int value) { if(lmap.count(key)) { auto iter=lmap[key]; lis.splice(lis.begin(),lis,iter); lis.begin()->value=value; lmap[key]=lis.begin(); return; } else { if(lis.size()==size) { lmap.erase(lis.back().key); lis.pop_back(); lis.push_front(CacheNode(key,value)); lmap[key]=lis.begin(); } else { lis.push_front(CacheNode(key,value)); lmap[key]=lis.begin(); } return; } } private: int size; list<CacheNode> lis; unordered_map<int,list<CacheNode>::iterator> lmap; };