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