import java.util.*;
class MyLRU{
static class LNode{
int key;
int val;
LNode preNode;
LNode nextNode;
LNode(){}
LNode(int key,int val){
this.key=key;
this.val=val;
}
}
LNode head,tail;
// 容量
int CAPACITY;
// 记录当前元素数目
int count;
MyLRU(int capacity){
head=new LNode(-1,0);
tail=new LNode(-2,0);
this.CAPACITY=capacity;
head.nextNode=tail;
tail.preNode=head;
}
static HashMap<Integer,LNode> nodeMap=new HashMap<>();
int query(LNode list, int key){
//直接查询HashMap,查找复杂度为O(1),若存在,则需要将节点重新插入队头
if(!nodeMap.containsKey(key)){
return 0;
}
else{
LNode curNode=nodeMap.get(key);
int result=curNode.val;
// 删除节点,并将重新插入节点
delete(curNode);
insert(list, curNode.key, curNode.val);
return result;
}
}
void insert(LNode list, int key, int val){
// 插入时首先看链表中是否存在,若存在,则删除再插入列表首,否则直接插入链表首
LNode curNode=new LNode(key,val);
if(nodeMap.containsKey(key)){
LNode oldNode=nodeMap.get(key);
delete(oldNode);
}
else{
// 若不存在,则保证插入后要满足容量要求,否则需要删除队尾元素再插入
if(count==CAPACITY){
delete(tail.preNode);
}
nodeMap.put(key,curNode);
count++;
}
curNode.nextNode=list.nextNode;
curNode.nextNode.preNode=curNode;
curNode.preNode=list;
list.nextNode=curNode;
}
void delete(LNode curNode){
// 因为首尾均有哨兵,所有可以直接删除
LNode p=curNode.preNode;
LNode q=curNode.nextNode;
p.nextNode=q;
q.preNode=p;
nodeMap.remove(curNode.key);
count--;
}
}
手撕LRU
于 2024-05-08 19:24:11 首次发布
200





