什么是LRU
LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法。也称缓存淘汰算法
如何实现
哈希加双向链表
来保证插入和查找的时间复杂度为o(1)
哈希用于查找
链表用于插入
方法一:调用jdk的LinkedHashMap(这个也是双向链表)
public class LRUTEST extends LinkedHashMap {
private int capatity;
public LRUTEST(int capatity){
super(capatity,0.75F,false);
this.capatity=capatity;
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest){
return super.size()>capatity;
}
}
方法二,自实现双向链表+哈希
package cn.sunshine.LRU;
import javax.xml.soap.Node;
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
//存储数据的节点Node
public class Node<K,V>{
K key;
V value;
Node<K,V> pre;
Node<K,V> next;
public Node(){
this.pre=this.next=null;
}
public Node(K key,V value){
this.key=key;
this.value=value;
this.pre=this.next=null;
}
}
//双向链表
public class DoubLinkedList<K,V>{
Node<K,V> head;
Node<K,V> tail;
public DoubLinkedList(){
head=new Node<>();
tail=new Node<>();
head.next=tail;
tail.pre=head;
}
public void addHead(Node<K,V> node){
node.next=head.next;
node.pre=head;
head.next.pre=node;
head.next=node;
}
public void romveNode(Node<K,V> node){
node.next.pre=node.pre;
node.pre.next=node.next;
node.pre=null;
node.next=null;
}
public Node getLast(){
return tail.pre;
}
}
private int capacity;
Map<Integer,Node<Integer,Integer>> map;
DoubLinkedList<Integer,Integer> doubLinkedList;
public LRUCache(int capacity) {
this.capacity=capacity;
map=new HashMap<>();
doubLinkedList=new DoubLinkedList<>();
}
public int get(int key) {
if (!map.containsKey(key)){
return -1;
}
Node<Integer,Integer> node=map.get(key);
doubLinkedList.romveNode(node);
doubLinkedList.addHead(node);
return node.value;
}
public void put(int key, int value) {
if (map.containsKey(key)){
Node<Integer,Integer> node=map.get(key);
node.value=value;
map.put(key,node);
doubLinkedList.romveNode(node);
doubLinkedList.addHead(node);
}else {
if (map.size()==capacity){//如果队列已满
Node lastNode=doubLinkedList.getLast();
map.remove(lastNode.key);
doubLinkedList.romveNode(lastNode);
}
Node newNode=new Node(key,value);
map.put(key,newNode);
doubLinkedList.addHead(newNode);
}
}
}