LeetCode 146. LRU 缓存
https://leetcode.cn/problems/lru-cache/
Solution(Java)
class LRUCache {
private int capacity;
private int curSize;
private Map<Integer, Node> cache;
private Node head;
private Node tail;
// 双向链表节点
static class Node {
Node pre;
Node next;
int key;
int val;
public Node() {}
public Node(int key, int val) {
this.key = key;
this.val = val;
}
public Node(int key, int val, Node pre, Node next) {
this.key = key;
this.val = val;
this.pre = pre;
this.next = next;
}
}
/**
* 初始化双向链表
*/
private void initLinkedList() {
this.head = new Node();
this.tail = new Node();
this.head.next = tail;
this.tail.pre = head;
}
/**
* 删除节点
*/
private void removeNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
/**
* 移动到头结点
*/
private void moveToHead(Node node) {
node.pre = head;
node.next = head.next;
head.next.pre = node;
head.next = node;
}
public LRUCache(int capacity) {
this.capacity = capacity;
this.curSize = 0;
this.cache = new HashMap<>();
initLinkedList();
}
/**
* 当节点不存在 return -1; 若存在,将节点移动到头结点
*/
public int get(int key) {
Node node = this.cache.get(key);
if (node != null) {
removeNode(node);
moveToHead(node);
return node.val;
}
return -1;
}
/**
* 将节点加入到头节点,若容器满,删除尾节点
*/
public void put(int key, int value) {
Node node = this.cache.get(key);
if (node != null) {
node.val = value;
removeNode(node);
moveToHead(node);
} else {
Node newNode = new Node(key, value);
moveToHead(newNode);
this.cache.put(key, newNode);
this.curSize++;
if (this.curSize > capacity) {
this.cache.remove(this.tail.pre.key);
removeNode(this.tail.pre);
this.curSize--;
}
}
}
}
/**
* 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);
*/