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.
In order to find efficient O (1), consider using hash table hash, in order to make the insert/delete efficient O (1), consider using a doubly linked list, so use a double-linked list and hash table combination.
GET (Key):
Hash hits node, moves node from list to table header, otherwise returns-1
SET (key, value):
Hash hits node, just update node in the hash and move node from list to table header.
Hash does not hit, you need to judge capacity. If the cache is full, you need to replace node in the cache and delete the footer element of list, the cache is not full, the node is inserted into the header, and the cache is updated.
1 structCachenode2 {3 intkey;4 intvalue;5Cachenode (intKintv): Key (k), value (v) {}6 };7 8 classlrucache{9 Public:TenLRUCache (intcapacity) One { ACacheSize =capacity; - } - the int Get(intkey) - { - if(Cachemap.find (key) = = Cachemap.end ())//Hit fail - return-1; + Cachelist.splice (Cachelist.begin (), Cachelist, Cachemap[key]); -Cachemap[key] =Cachelist.begin (); + returnCachemap[key]->value; A } at - void Set(intKeyintvalue) - { - if(Cachemap.find (key) = = Cachemap.end ())//Hit fail - { - Cachenode CacheItem (key, value); in if(cachemap.size () = = cacheSize)//Cache is full - { to cachemap.erase (Cachelist.back (). key); + Cachelist.pop_back (); - } the Cachelist.push_front (cacheItem); *Cachemap[key] =Cachelist.begin (); $ }Panax Notoginseng Else //Hit success - { theCachemap[key]->value =value; + Cachelist.splice (Cachelist.begin (), Cachelist, Cachemap[key]); ACachemap[key] =Cachelist.begin (); the } + } - $ Private: $ intcacheSize; -unordered_map<int, list<cachenode>::iterator>Cachemap; -List<cachenode>cachelist; the};
Leetcode 146. LRU Cache