Leetcode | LRU Cache

Source: Internet
Author: User

Design and implement a data structure for least recently used (LRU) cache. It shocould support the following operations:getAndset.

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 shocould invalidate the least recently used item before inserting a new item.


That is, design an LRU algorithm. when the container is full, there is an LRU replacement rule. At the beginning, I understood the LRU incorrectly and thought it was necessary to record the number of accesses to each element, later, we found that this is not necessary. The essence of LRU replacement is to replace the elements that have not been accessed for the longest time. Both set and get are regarded as access operations. Therefore, the solution is that the elements in the cache are ordered, sort by the Access time. When the last accessed element is in the header (or tail), you can directly Delete the tail (or head) element when replacing it. If no sequential sequence is used, therefore, you need to record the last access time of each element. When you replace it, traverse the entire sequence and find the replacement with the longest time, but this will time out. Therefore, the sequence should be kept in sequence.

According to the requirements of the questions, we need to implement the get and set functions. To meet the Random storage requirements, we first think of arrays. If we use a linked list, there will be an O (n) Access time. However, it is necessary to maintain the least used queue, which is usually put at the front and rarely put at the back. This requires us to have good deletion and insertion operations on the nodes, which reminds us of the linked list, because the deletion and insertion of arrays are O (n) complex.
So can we maintain a data structure so that the access and insert/delete operations are O (1) complex? The answer is yes. That is, you can use list to save the element, insert it in the header, and delete it at the end. Each time you access the element, you can move it to the header (the complexity of moving an element to the header in a two-way linked list is O (1 )); record the position of the element with a hash_map.


Difficulty: How can I re-adjust the sequence of each element to move the accessed element to the header ???

Solution: only the list of containers in STL can easily adjust the order, that is, the splice method, it inserts an element at a certain position of a list or an element at a certain range into the current list. Of course, if the two are in the same list, then, adjust the order of some elements in the list. The introduction of the splice method here, because its parameter is the location iterator, we need to record the iterator information corresponding to the element key. You can use map, however, because map is an ordered sequence implemented by the balancing tree, its access time complexity is O (logn). because we do not need to order it, we can use hash_map, that is, unordered_map.


The Code is as follows:

Struct node {int key; int value; node (int K, int V): Key (K), value (v) {}};/** note that the overall idea is, you can use bidirectional list to place this element in the list header each time you set or get an element. You do not need to count the number of operations on each element, in fact, LRU means * That the end element of the List is replaced based on the time when the element is last accessed. * STL tips: 1. Use the find method of map to determine whether the key already exists. The returned value is compared with the end iterator of map. 2. Use unordered_map, Which is hash_map, the access time is O (1). It stores the position iterator of the element to facilitate the splice function to call * List. the splice (Position, list, element_pos) function is used to insert the elements at element_pos in the list to the position. To move an element to the list header */class lrucache {int size; List <node> values; unordered_map <int, list <node >:: iterator> positions; public: lrucache (INT capacity) {size = capacity;} int get (INT key) {If (positions. find (key )! = Positions. end () {values. splice (values. begin (), values, positions [Key]); positions [Key] = values. begin (); return values. begin ()-> value;} return-1;} void set (INT key, int value) {If (positions. find (key )! = Positions. end () {values. splice (values. begin (), values, positions [Key]); // move the accessed element to the values header. begin ()-> value = value; positions [Key] = values. begin (); // update the position. Note that the position here is only a pointer. when the key is squeezed to another position in the list, the position saved in positions will also change, because it is just a pointer to this node} else if (values. size () <size) {values. push_front (node (Key, value); positions [Key] = values. begin ();} else {node last = values. back (); values. pop_back (); positions. erase (last. key); values. push_front (node (Key, value); positions [Key] = values. begin ();}}};


Reference link:

Http://www.myexception.cn/program/1598814.html

Http://www.cnblogs.com/x1957/p/3485053.html





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.