package common;
import java.util.HashMap;
import java.util.Map;
/**
* @author : zhaoliang
* @program :newCoder
* @description : 双向链表+HashMap
* @create : 2020/12/20 09:19
*/
public class LRUCache {
class ListNode{
int key,val;
ListNode next = null;
ListNode pre = null;
ListNode(int key,int val){
this.key = key;
this.val = val;
}
}
private int capacity;
private Map<Integer,ListNode> map;
private ListNode head;
private ListNode tail;
public LRUCache(int capacity){
this.capacity = capacity;
this.map = new HashMap<>();
head = new ListNode(-1,-1);
tail = new ListNode(-1,-1);
head.next = tail;
tail.pre = head;
}
public int get(int key){
if(!map.containsKey(key)){
return -1;
}
ListNode node = map.get(key);
//删除节点
node.pre.next = node.next;
node.next.pre = node.pre;
//移动到尾部
moveToTail(node);
return node.val;
}
//把节点移动到尾巴
private void moveToTail(ListNode node) {
node.pre = tail.pre;
tail.pre = node;
node.pre.next = node;
node.next = tail;
}
public void put(int key,int value){
//直接调用get,如果存在移动到表尾,不存在放入判断是否超出阈值
if (get(key)!=-1){
map.get(key).val = value;
return;
}
//不存在,new一个,超出容量,把头去掉
ListNode node = new ListNode(key,value);
map.put(key,node);
moveToTail(node);
if (map.size() > capacity){
map.remove(head.next.key);
head.next = head.next.next;
head.next.pre = head;
}
}
}
常见算法-双链表+HashMap实现LRU
最新推荐文章于 2022-06-26 23:47:50 发布