package com.company.test.设计LRU缓存结构;
import java.util.*;
/**
* @author xienl
* @description 设计LRU缓存结构
* @date 2022/7/18
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution(2);
/* solution.set(1,0);
solution.set(2,2);
System.out.println(solution.get(1));
solution.set(3,3);
System.out.println(solution.get(2));
solution.set(4,4);
System.out.println(solution.get(1));
System.out.println(solution.get(3));
System.out.println(solution.get(4));*/
solution.set(1,1);
solution.set(2,2);
solution.set(1,2);
solution.set(3,3);
System.out.println(solution.get(1));
}
Map<Integer, Node> cache;
int size;
int capacity;
Node head;
Node tail;
public Solution(int capacity) {
// write code here
cache = new HashMap<>();
size = 0;
this.capacity = capacity;
head = new Node();
tail = new Node();
head.next = tail;
tail.pre = head;
}
private void remove(Node node){
node.pre.next = node.next;
node.next.pre = node.pre;
}
private void addHade(Node node){
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
private void moveToHead(Node node){
remove(node);
addHade(node);
}
private Node deletetail(){
Node tail = this.tail.pre;
remove(tail);
return tail;
}
public int get(int key) {
// write code here
Node node = cache.get(key);
if (node == null){
return -1;
}
moveToHead(node);
return node.value;
}
public void set(int key, int value) {
// write code here
Node node = cache.get(key);
if (node == null){
Node newNode = new Node(key, value);
cache.put(key, newNode);
addHade(newNode);
size++;
if (size > capacity){
Node tail = deletetail();
cache.remove(tail.key);
size--;
}
} else{
cache.get(key).value = value;
moveToHead(node);
}
}
class Node {
int key;
int value;
Node pre;
Node next;
public Node (){};
public Node (int key, int value){
this.key = key;
this.value = value;
}
}
}
08-06
105
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-07
1162
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)