title :
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 ('ll 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 is reached its capacity, it should invalidate the least recently used item before inserting a new item.
Code :
classlrucache{Private: structcachenode{intkey; intvalue; Cachenode (intKintv): Key (k), value (v) {}}; Std::list<CacheNode>cachelist; Std::map<int, std::list<cachenode>::iterator>Cachemap; intcapacity; Public: LRUCache (intcapacity) { This->capacity =capacity; } int Get(intkey) { if(Cachemap.find (key) = = Cachemap.end ())return-1; Cachelist.splice (Cachelist.begin (), Cachelist, Cachemap[key]); Cachemap[key]=Cachelist.begin (); returnCachemap[key]->value; } void Set(intKeyintvalue) { if(Cachemap.find (key) = =Cachemap.end ()) { if(cachelist.size () = =capacity) {Cachemap.erase (Cachelist.back (). key); Cachelist.pop_back (); } cachelist.push_front (Cachenode (Key,value)); Cachemap[key]=Cachelist.begin (); } Else{Cachemap[key]->value =value; Cachelist.splice (Cachelist.begin (), Cachelist, Cachemap[key]); Cachemap[key]=Cachelist.begin (); } }};
Tips:
This topic is directly referenced on-line solution.
Record several questions at the time:
1. Why combine list and hashmap two kinds of data structure, only use HashMap a kind of data structure not?
Because, if the cache is full, HashMap is unable to know which element is "least likely to be accessed", but using a doubly linked list (STD::LIST) structure can easily determine this.
2. Why is there a key member in Cachenode?
If we want to remove the "most unlikely element to be accessed", we know that the element itself is value in the last position of the list, but how do we know where the element in the Hasmap is going to be deleted? Therefore, we need to save the key and value in the Cachenode structure. This allows you to know where in the hashmap you want to delete by using the last element of the list.
"LRU Cache" cpp