146. LRU 缓存
作者:互联网
class LRUCache {
class DoubleList{
public int key, val;
public DoubleList prev, next;
public DoubleList(){}
public DoubleList(int key, int val){
this.key = key;
this.val = val;
}
}
public HashMap<Integer, DoubleList> map = new HashMap<>();
public DoubleList head, tail;
public int size;
public int cap;
public LRUCache(int cap){
this.cap = cap;
this.size = 0;
head = new DoubleList();
tail = new DoubleList();
head.next = tail;
tail.prev = head;
}
public int get(int key){
// 不存在直接返回-1
if (!map.containsKey(key)){
return -1;
}
// 存在就返回值,并将该节点移到表头(先删除,再插入到表头)
turnToHead(map.get(key));
return map.get(key).val;
}
public void put(int key, int val){
DoubleList node = map.get(key);
if (node == null){ // 哈希表中不存在该元素
if (size == cap){ // 如果链表长度达到设定上限,就删除表尾元素,即最近最久未用元素
DoubleList nn = tail.prev;
removeNode(nn);
map.remove(nn.key);
size--;
}
DoubleList newNode = new DoubleList(key, val); // 新加入的元素要放在表头
map.put(key, newNode);
addFirst(newNode);
size++;
}else{ // 哈希表中存在该元素,直接修改元素的值,并放到表头
node.val = val;
turnToHead(node);
}
}
public void removeNode(DoubleList node){ // 移除元素
node.prev.next = node.next;
node.next.prev = node.prev;
}
public void addFirst(DoubleList node){ // 把元素移到插入到表头
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
public void turnToHead(DoubleList node){ // 先删除,再插入表头
removeNode(node);
addFirst(node);
}
}
标签:146,node,缓存,val,int,LRU,key,DoubleList,public 来源: https://www.cnblogs.com/lchen-java/p/16408160.html