[Leetcode] LRU 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.

Solution:

Data

The typical implementation of LRU is hash map + doubly linked list that a doubly linked list is used to store data nodes, and it is stored by the time that the node was most recently used. If a node is accessed, we have reason to believe that it will be accessed more than any other node over the next period of time. So, we put it on the head of the doubly linked list. When we insert a node into the two-way link, it is also possible that we will soon be using it, as well as inserting it into the head. We use this method to constantly adjust the two-way list, the end of the linked list is naturally the most recent period of time, the longest unused nodes. So, when our cache is full, what needs to be replaced is the last node in the doubly linked list (not the tail node, which does not store the actual content).

The following is a doubly linked list, noting that the end-to-end nodes do not store actual content:

头 --> 结 --> 结 --> 结 --> 尾结     点     点     点     结点 <-- 1  <-- 2 <-- 3  <-- 点

If the cache is full, we have to replace the node 3.

What is the function of a hash table? If there is no hash table, we have to access a node, we need to search sequentially, time complexity is O (n). Using a hash table allows us to find the node we want to access at the time of O (1), or the return is not found.

[Leetcode] LRU 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.