class LRUCache {
class Node{
int key;
int val;
Node pre;
Node next;
public Node(){}
public Node(int key,int val){
this.key = key;
this.val = val;
}
}
private int capacity;
private int size;
private Node head;//伪头结点
private Node tail;//伪尾节点
private HashMap<Integer,Node> map = new HashMap<Integer,Node>();
public LRUCache(int capacity) {
this.capacity = capacity;
this.size = 0;
this.head = new Node();
this.tail = new Node();
head.next = tail;
tail.pre = head;
}
//在链表中将该结点移除
public void removeNode(Node node){
node.pre.next = node.next;
node.next.pre = node.pre;
}
//将结点添加到头结点之后
public void addFirst(Node node){
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
//将结点移动到第一个
public void moveFirst(Node node){
removeNode(node);
addFirst(node);
}
//删除最后一个结点
public Node removeLast(){
Node last = tail.pre;
removeNode(last);
return last;
}
public int get(int key) {
//从哈希表中根据key定位到结点
Node node = map.get(key);
//如果结点存在就将结点移动到首位。
if(node!=null){
moveFirst(node);
return node.val;
}
//没找到返回-1
return -1;
}
public void put(int key, int value) {
Node node = map.get(key);
//如果存在该结点,只用修改值,然后将结点移动到链表首位就好了
if(node!=null){
node.val = value;
moveFirst(node);
}else{
//不存在,就创建新节点
Node newNode = new Node(key,value);
//并将新结点存入哈希表中
map.put(key,newNode);
addFirst(newNode);
size++;
//如果当前结点超过了容量,就要将最少访问的结点删除
if(size>capacity){
Node last = removeLast();
map.remove(last.key);
size--;
}
}
}
}
LeetCode日记 146.LRU缓存机制
最新推荐文章于 2024-04-18 18:49:31 发布