LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用)
缓存机制。它应该支持以下操作: 获取数据 get
和 写入数据 put
。
获取数据 get(key
) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value)
- 如果密钥已经存在,则变更其数据值;如果密钥不存在,则插入该组「密钥/数据值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
示例:
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
思路
LRU
缓存设计一般都是HashMap
和LinkedList
,HashMap
维护get
和put
的操作,LinkedList
维护缓存的存储顺序。
添加一个元素时,如果HashMap
里没有,则新建一个Node
,添加到头部;如果HashMap
里存在,则更新他的Value,然后将其移到开头。
若添加一个元素使得存储大小超过限制,则删除最后一个元素。
访问一个元素的时候,要将其放在头部。
解答
class LRUCache {
private Map<Integer, Node> cache;
private int size;
private int capacity;
private Node head, end;
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
cache = new HashMap();
head = new Node();
end = new Node();
head.next = end;
end.pre = head;
}
public int get(int key) {
Node node = cache.get(key);
if (node == null) return -1;
moveToHead(node);
return node.val;
}
public void put(int key, int val) {
Node node = cache.get(key);
if (node == null) {
Node newNode = new Node(key, val);
cache.put(key, newNode);
addToHead(newNode);
size++;
if (size > capacity) {
Node tail = removeLastNode();
cache.remove(tail.key);
size--;
}
} else {
node.val = val;
moveToHead(node);
}
}
private class Node {
public int key, val;
public Node pre, next;
public Node () {}
public Node (int key, int val) { this.key = key; this.val = val; }
}
private void addToHead(Node node) {
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
private void moveToHead(Node node) {
removeNode(node);
addToHead(node);
}
private void removeNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
private Node removeLastNode() {
Node pre = end.pre;
removeNode(pre);
return pre;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/