Leetcode OJ:LRU Cache (recently used cache)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.