LRU原理
LRU算法的特点是:当资源不足需要清除数据时,最近被使用过的数据不会被清除(即:只会清除最近没有使用的数据)。要实现这个特点,就需要维护一个链表来表达数据被使用的顺序。同时我们知道链表的查询效率较低,所以需要结合散列表的特点(查询效率高)来实现这个数据结构。
代码实现
使用 HashMap + 自定义双链表
实现。
public class LruCache {
HashMap<Integer, Node> map = new HashMap();
Node head = null;
Node tail = null;
int capacity = 0;
int size = 0;
/**
* 自定义双向链表。
*/
class Node {
int key;
int value;
Node pre;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
public LruCache(int capacity) {
this.capacity = capacity;
// 构建两个虚拟节点,避免在对真实Node数据进行node.pre和node.next操作时,出现空指针的问题。
this.head = new Node(-1, -1);
this.tail = new Node(-1, -1);
head.next = tail;
tail.pre = head;
}
public int get(int key) {
Node node = map.get(key);
if (node != null) {
removeNode(node);
addToHead(node);
return node.value;
}
return -1;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node != null) {
removeNode(node);
addToHead(node);
node.value = value;
return;
}
node = new Node(key, value);
map.put(key, node);
addToHead(node);
++size;
if (size > capacity) {
Node remove = removeTail();
map.remove(remove.key);
--size;
}
}
// 将新增Node添加到虚拟节点head和head.next之间。
private void addToHead(Node node) {
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
private Node removeTail() {
Node remove = tail.pre;
removeNode(remove);
return remove;
}
// 移除一个Node,即将Node节点前后两个节点进行关联。
private void removeNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
}
测试代码:
public static void main(String[] args) {
LruCache cache = new LruCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
}