当前位置:网站首页>Roll in Dachang series LRU cache elimination algorithm
Roll in Dachang series LRU cache elimination algorithm
2022-06-21 06:17:00 【It snows at night when the boat is moored. He can expect it in 】
LRU What is it? ?
LRU yes Least Recently Used Abbreviation , Least recently used , Is a commonly used memory elimination data algorithm , That is, eliminate the least recently used cache data .
LRU functional requirement
Please design and implement a meeting LRU ( Recently at least use ) Cache constrained data structures .
Realization LRUCache class :
LRUCache(int capacity) With Positive integer As capacity capacity initialization LRU cache . int get(int key) If the keyword key In the cache , The value of the keyword is returned , Otherwise return to -1 . void put(int key, int value) If the keyword key Already exist , Change its data value value ; If it doesn't exist , Then insert the group into the cache key-value . If the insert operation causes the number of keywords to exceed capacity , Should be Eviction The longest unused keyword . function get and put Must be O(1) The average time complexity of running .
Example :
Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]
explain
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // The cache is {1=1}
lRUCache.put(2, 2); // The cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // This operation causes the keyword to 2 To void , The cache is {1=1, 3=3}
lRUCache.get(2); // return -1 ( Not found )
lRUCache.put(4, 4); // This operation causes the keyword to 1 To void , The cache is {4=4, 3=3}
lRUCache.get(1); // return -1 ( Not found )
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Realization
analysis : To eliminate the least recently used memory data , So how to distinguish which memory data has not been used recently ?
May adopt Map structure ( Query operation O(1)) + Double linked list ( The header records old data , The tail records new data )
In a two-way list , Add the data according to the tail , Those close to the head represent those who are earlier in time ( Join the team early ), Far from the head means it's a little late ( After that, I joined the team ), Add... According to the tail , Head deletion principle , Close to the head represents the least recently used data , That is to eliminate the data in the head of the linked list, which represents the least recently used data .
The two-way linked list operation is summarized as follows :
Add nodes at the end Get elements (get operation ) That is, the element , You need to move the element to the end of the linked list ( Represents the recent use of this data ) Additive elements (put operation ) That is, the element , If the element exists , Update element data , At the same time, you also need to move the element to the end of the linked list ( Represents the recent use of this data ), If the element does not exist , It is directly added to the tail of the linked list . When adding elements , Capacity needs to be considered , If it exceeds the current capacity , Then remove the head element of the linked list ( Represents data that has not been operated recently )
public class LRUCache {
private MyCache<Integer, Integer> cache;
public LRUCache(int capacity) {
cache = new MyCache<>(capacity);
}
public int get(int key) {
Integer ans = cache.get(key);
return ans == null ? -1 : ans;
}
public void put(int key, int value) {
cache.set(key, value);
}
// The node structure
public static class Node<K, V> {
public K key;
public V value;
public Node<K, V> pre;
public Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
// Double linked list structure
public static class NodeDoubleLinkedList<K, V> {
private Node<K, V> head;
private Node<K, V> tail;
public NodeDoubleLinkedList() {
head = null;
tail = null;
}
// Add nodes at the end
public void addNode(Node<K, V> newNode) {
if (newNode == null) {
return;
}
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.pre = tail;
tail = newNode;
}
}
// Move the nodes on the linked list to the tail
public void moveNodeToTail(Node<K, V> node) {
if (tail == node) {
return;
}
// node Not the tail
if (head == node) {
head = node.next;
head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
node.pre = tail;
node.next = null;
tail.next = node;
tail = node;
}
// Remove the head node
public Node<K, V> removeHead() {
if (head == null) {
return null;
}
Node<K, V> res = head;
if (head == tail) { // When there is only one node in the linked list
head = null;
tail = null;
} else {
head = res.next;
res.next = null;
head.pre = null;
}
return res;
}
}
public static class MyCache<K, V> {
private HashMap<K, Node<K, V>> keyNodeMap;
private NodeDoubleLinkedList<K, V> nodeList;
private final int capacity;
public MyCache(int cap) {
if (cap < 1) {
throw new RuntimeException("should be more than 0.");
}
keyNodeMap = new HashMap<>();
nodeList = new NodeDoubleLinkedList<>();
capacity = cap;
}
public V get(K key) {
if (keyNodeMap.containsKey(key)) {
Node<K, V> res = keyNodeMap.get(key);
nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (keyNodeMap.containsKey(key)) {
Node<K, V> node = keyNodeMap.get(key);
node.value = value;
nodeList.moveNodeToTail(node);
} else {
if (keyNodeMap.size() == capacity) {
removeMostUnusedCache();
}
Node<K, V> newNode = new Node<>(key, value);
keyNodeMap.put(key, newNode);
nodeList.addNode(newNode);
}
}
private void removeMostUnusedCache() {
Node<K, V> removeNode = nodeList.removeHead();
keyNodeMap.remove(removeNode.key);
}
}
}
- END - 边栏推荐
- The time plug-in is used for the establishment time, but when modifying parameters on the web page, if the time is not modified, an error will be reported when saving it for the first time, and it can
- xshell7远程连接服务器,挂起进程一直维持程序的运行
- tf. QueueBase
- 双调查找:数组先递增后递减
- Digital signal processing-07-dds IP application example
- WordPress pseudo original tool - update website one click pseudo original publishing software
- Aurora8B10B IP使用 -02- IP功能设计技巧
- 直击2022互联网大裁员:繁花落地,一地鸡毛
- tf.Operation
- 第一章:数据库系统概述(数据库期末复习)
猜你喜欢

Aurora8B10B IP使用 -05- 收发测试应用示例

【数据挖掘】期末复习 第五章

Aurora8b10b IP usage-05-transceiver test application example
![[[graduation season · advanced technology Er] - experience shared by senior students](/img/15/720dac05ebba3ead1b82b15f15daa6.png)
[[graduation season · advanced technology Er] - experience shared by senior students

The time plug-in is used for the establishment time, but when modifying parameters on the web page, if the time is not modified, an error will be reported when saving it for the first time, and it can

模块 14 - 15:网络应用通信考试

正则表达式基础

Digital signal processing-07-dds IP application example

记录 Navicat 连接 PostgreSQL 无法显示对应表的问题

397 linked list (206. reverse linked list & 24. exchange nodes in the linked list in pairs & 19. delete the penultimate node of the linked list & interview question 02.07. link list intersection & 142
随机推荐
[JVM] method area
tf.Operation
FPGA - 7系列 FPGA SelectIO -06- 逻辑资源之ODELAY
计组必刷题:存储系统(已完结,附详细解析)
FPGA - 7 Series FPGA selectio -05- logic of logic resources
Detailed explanation of balanced binary tree is easy to understand
tf.compat.v1.get_default_graph
FPGA - 7 Series FPGA selectio -03- ILOGIC of logic resources
【【毕业季·进击的技术er】------老学长心得分享
NumPy的广播机制
IP - RF data converter -04- API User Guide - ADC status indication function
FPGA - 7系列 FPGA SelectIO -01- 简介与DCI技术简介
leetcode 675. Cutting down trees for golf competitions - (day29)
Contos7 installing SVN server
端口占用解决
fastdfs集群
Gpushare- members are coming online~
Metasploit intrusion win7
BN的一些细节
Judge whether a tree is a complete binary tree