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.
With the recent use of the cache, it is possible to use a map to see the key and value feeling. Maintain a cache with a list, and then map to each node of the corresponding cache.
Note that the most recent use, whether get or set, belongs to the most recently used category, as shown in the code below:
1 classlrucache{2 structcachenode{3 intkey;4 intVal;5Cachenode (intKintv):6 key (k), Val (v) {}7 };8 Public:9LRUCache (intcapacity) {TenSize =capacity; One } A - int Get(intkey) { - if(Cachemap.find (key)! =Cachemap.end ()) { theAuto it =Cachemap[key]; - Cachelist.splice (Cachelist.begin (), cachelist, it); -Cachemap[key] =Cachelist.begin (); - returnCachelist.begin ()Val; +}Else - return-1; + } A at void Set(intKeyintvalue) { - if(Cachemap.find (key)! = Cachemap.end ()) {//the element exists in the list -Auto it =Cachemap[key]; - Cachelist.splice (Cachelist.begin (), cachelist, it); -Cachemap[key] = =Cachelist.begin (); -Cachelist.begin ()->val =value; in}Else{//The element does not exist in the list - if(cachelist.size () = = This-size) { to cachemap.erase (Cachelist.back (). key); + Cachelist.pop_back (); - } the Cachelist.push_front (Cachenode (key, value)); *Cachemap[key] =Cachelist.begin (); $ }Panax Notoginseng } - Private: the intsize; +List<cachenode>cachelist; Aunordered_map<int, list<cachenode>::iterator>Cachemap; the};
Leetcode OJ:LRU Cache (recently used cache)