1. 什么是LRU Cache?
在LeetCode上看到一个LRU Cache实现的题目,题目描述是这样的:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
简单的说,就是保证基本的get和set的功能的同时,还要保证最近访问(get或put)的节点保持在限定容量的Cache中,如果超过容量则应该把LRU(近期最少使用)的节点删除掉。
那么我们思考一个问题:如何设计实现一个LRU Cache?
那么,我们可能需要使用类似这样的数据结构去实现这个LRU Cache:
当我们在get or set一个节点时都会把操作的这个节点移动到tail节点处,代表这个是最新操作的节点,head节点永远指向最老的节点,当超过设定的容量时,我们就删除head节点指向的最老节点。
其实上图就像是个LinkedHashMap,这样做的好处是,get和set在不冲突的情况下可以保证O(1)的复杂度,同时,也可以通过双向链表来保证LRU的删除和更新操作也能保证O(1)的复杂度。
当然上图可以简化一下head节点和tail节点变成一个head节点,形成一个环,这样head的next指向最旧的节点,prev指向最新的节点。
2.实现思路
在学习了HashMap和LinkedHashMap后,是不是觉得这俩数据结构简直太适合做LRU Cache了!那么动手实现一下:
基于HashMap和双向链表的实现
public class LRUCache<K , V> {
class Node<K,V> {
Node pre;
Node next;
private final K key;
V val;
Node(K k, V v) {
key = k;
val = v;
}
}
Map<K, Node> map = new HashMap<K, Node>();
// The head (eldest) of the doubly linked list.
Node head;
// The tail (youngest) of the doubly linked list.
Node tail;
int cap;
public LRUCache(int capacity) {
cap = capacity;
head = new Node(null, null);
tail = new Node(null, null);
head.next = tail;
tail.pre = head;
}
public V get(K key) {
Node n = map.get(key);
if(n!=null) {
removeNode(n);
appendTail(n);
return (V) n.val;
}
return null;
}
public void set(K key, V value) {
Node n = map.get(key);
// existed
if(n!=null) {
n.val = value;
map.put(key, n);
removeNode(n);
appendTail(n);
return;
}
if(map.size() == cap) {
removeLast();
}
n = new Node(key, value);
// youngest node append tail
appendTail(n);
map.put(key, n);
}
//移除最近最少使用的节点,注意此节点就是head.next指向的节点
public void removeLast() {
Node tmp = head.next;
removeNode(tmp);
map.remove(tmp.key);
}
//移除某个节点,并将此节点的前后节点连接起来
private void removeNode(Node n){
n.pre.next = n.next;
n.next.pre = n.pre;
}
//将节点加入到队列的尾部,尾部代表最近使用的节点
private void appendTail(Node n) {
n.next = tail;
n.pre = tail.pre;
tail.pre.next = n;
tail.pre = n;
}
}
基于LinkedHashMap的实现
public class LRUCache<K , V> {
private int capacity;
private Map<K, V> cache;
public LRUCache(final int capacity) {
this.capacity = capacity;
this.cache = new java.util.LinkedHashMap<K, V> (capacity, 0.75f, true) {
// 定义put后的移除规则,大于容量就删除eldest
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
};
}
public V get(K key) {
if (cache.containsKey(key)) {
return cache.get(key);
} else
return null;
}
public void set(K key, V value) {
cache.put(key, value);
}
}
完
更多精彩Android技术可以关注我们的微信公众号,扫一扫下方的二维码或搜索关注公众号:
Android老鸟