算法之手写LRU缓存
解决:
双向链表+hash表
Get没有值直接返回-1,有值的情况下,get到位置,移除当前前后关系,把当前元素后移。
/**代码实现**/
package com.andong.demo.LinkList.双向链表LRU缓存;
import java.util.HashMap;
import java.util.Map;
/**
* @Author andong
* @Date: 2021/04/09/19:27
* 最近很少使用基于时间(淘汰最久没有使用的那个节点) 基于双向链表+hash表实现
* @Description:
*/
public class LRUCache {
class CacheNode{
CacheNode pre;
CacheNode next;
int key;
int value;
CacheNode(int key,int value){
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
public int capacity ;
private Map<Integer,CacheNode> map = new HashMap<Integer, CacheNode>();
private CacheNode head = new CacheNode(-1, -1);
private CacheNode tail = new CacheNode(-1, -1);
public LRUCache(int capacity) {
this.capacity = capacity;
tail.pre = head;
head.next = tail;
}
private int get(int key){
if(!map.containsKey(key)){
return -1;
}
CacheNode currentNode = map.get(key);
currentNode.pre.next = currentNode.next;
currentNode.next.pre = currentNode.pre;
moveToTail(currentNode);
return map.get(key).value;
}
private void moveToTail(CacheNode current) {
current.pre = tail.pre;
tail.pre = current;
tail.pre.next = current;
current.next = tail;
}
}