LRU缓存
题目
实现 LRUCache 类:
- LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
- int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
- void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
来源:力扣(LeetCode)
链接
思路
维护一个双向链表和哈希表,哈希表存放键和对应的链表结点,双向链表的头为最久未使用的值,尾为最近使用的值,故去掉最久未使用的值只需移除链表头结点;更新最近使用的值只需将对应结点移到链表尾
class LRUCache {
class Node {
int key;
int value;
Node last;
Node next;
Node() {};
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
int capacity; // 容量
HashMap<Integer, Node> map;
Node head; // 双向链表头
Node tail; // 双向链表尾
LRUCache(int cap) {
capacity = cap;
map = new HashMap<>();
head = null;
tail = null;
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
} else {
Node node = map.get(key);
moveNodeToTail(node);
return node.value;
}
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
moveNodeToTail(node);
} else {
Node newNode = new Node(key, value);
map.put(key, newNode);
addNode(newNode);
if (map.size() > capacity) { // 检查是否超出容量,若超出则移除链表头结点
Node head = removeHead();
map.remove(head.key);
}
}
}
public void addNode(Node node) {
if (node == null) {
return;
}
// 若链表中无结点,则将头尾都指向新结点;否则将新结点挂在尾部
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
node.last = tail;
tail = node;
}
}
public void moveNodeToTail(Node node) {
if (node == null || head == tail || node == tail) { // 若链表只有一个结点,或者当前结点就是尾结点,直接return即可
return;
}
if (node == head) {
head = node.next;
head.last = null;
} else {
node.last.next = node.next;
node.next.last = node.last;
}
tail.next = node;
node.last = tail;
node.next = null;
tail = node;
}
public Node removeHead() {
if (head == null) {
return null;
}
Node res = head;
if (head == tail) {
head = null;
tail = null;
} else {
head = res.next;
res.next = null;
head.last = null;
}
return res;
}
}