[Question]
Design and implement a data structure for least recently used (LRU) cache. It shocould support the following operations:get
Andset
.
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.
Question]
Implement LRU Policy
1. Get value based on key
2. When inserting key-value, you must delete the LRU item
[Idea]
Maintain the corresponding <key, value> pair of a map record
In order to simulate the sequence of keys, you need to maintain a sequence list. The closer the node to which the key is located, the shorter the interval of the sequence query from the current time.
When inserting or inserting a key, you need to find the corresponding key from the list and adjust it to the list.
There are two problems: one is searching, and the other is moving to the end.
Assume that the sequential table is used to search for O (N) and move O (n). The time cost is too high when the cache size is very large.
Therefore, two-way linked list is used for processing.
[Code]
Struct node {int key; int val; node * Prev; node * Next; node (int K, int V): Key (K), Val (v) {Prev = NULL; next = NULL ;}}; class lrucache {PRIVATE: node * head; node * tail; int capacity; Map <int, node *> cache; public: lrucache (INT capacity) {This-> head = NULL; this-> tail = NULL; this-> capacity = capacity;} void move2tail (node * node) {If (node = tail) return; if (node = head) {head = node-> next; head-> Prev = NULL; tail-> next = node; node-> Prev = tail; tail = node; tail-> next = NULL;} else {node-> Prev-> next = node-> next; node-> next-> Prev = node-> Prev; tail-> next = node; node-> Prev = tail; tail = node; tail-> next = NULL;} int get (INT key) {If (this-> cache. find (key) = This-> cache. end () Return-1; move2tail (this-> cache [Key]); return this-> cache [Key]-> val;} void set (INT key, int value) {If (this-> cache. find (key) = This-> cache. end () {// The cache does not contain if (this-> capacity = 0) {// The cache is full. // Delete the header node this-> cache. erase (Head-> key); Head = head-> next; If (head) Head-> Prev = NULL; else tail = NULL ;} else {// The cache is not full. This-> capacity --;} // Add node * newnode = new node (Key, value ); this-> cache [Key] = newnode; If (tail) {tail-> next = newnode; newnode-> Prev = tail; tail = newnode; tail-> next = NULL;} else {head = tail = newnode;} else {// cache already has this-> cache [Key]-> val = value; move2tail (this-> cache [Key]) ;}};