LRU(least recently used),最近最久未使用置换算法
是一种页面置换算法,操作系统中当内存空间不足时,会将内存中暂时不用的信息置换到外存(磁盘)中,用的时候再换进来。
所谓最近最久未使用置换算法就是优先将最近未使用(最早进来)的页面置换出去。根据局部性原理,认为最近使用的页面之后再次被使用的概率最大。因此该算法是合理的。
一种硬件解决方案是,对于每一个页面记录自上次访问经过的时间,置换时只需要置换该值最大的页面即可。然而该方式需要硬件电路的支持。
软件实现如下:
使用双端链表+哈希表的结构实现。需实现get(), put()方法。
使用双端链表维护从头到尾优先级递增。增加元素时在尾上加,删除元素时在头上删除。访问时,先通过hashmap找到该节点。然后将该节点从链表中删除,再加到尾部,如此保证了最近访问的优先级最高。
具体代码如下:
class LRUCache {
public static class Node{
int key;
int val;
Node pre;
Node next;
public Node(int key, int val){
this.key = key;
this.val = val;
}
}
private int capacity;
private int length;
private Map<Integer, Node> map;
private Node head; // 从头到尾优先级递减
private Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.length = 0;
this.map = new HashMap<>();
head = new Node(-1, -1);
tail = new Node(-1, -1);
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
Node cur = map.get(key);
// 删除结点
cur.pre.next = cur.next;
cur.next.pre = cur.pre;
// 插回到头上
cur.pre = head;
cur.next = head.next;
head.next.pre = cur;
head.next = cur;
return cur.val;
}
public void put(int key, int value) {
Node cur = null;
if(map.containsKey(key)){
cur = map.get(key);
cur.val = value;
get(key);
}else{
// 将该节点插到头上
cur = new Node(key, value);
map.put(key, cur);
cur.pre = head;
cur.next = head.next;
head.next.pre = cur;
head.next = cur;
length++;
}
if(length > capacity){
// 删除尾处的结点
length--;
Node temp = tail.pre;
temp.pre.next = tail;
tail.pre = temp.pre;
temp.next = null;
temp.pre = null;
map.remove(temp.key);
}
}
}