LeetCode 146. LRU缓存机制(Java代码)
原题链接
中等
作者:
火球大的脸盆
,
2024-11-04 23:20:12
,
所有人可见
,
阅读 4
LRU缓存,Java 代码
class LRUCache {
class LinkedNode {
Integer key;
Integer value;
LinkedNode prev;
LinkedNode next;
LinkedNode (Integer key, Integer value) {
this.key = key;
this.value = value;
}
LinkedNode () {
}
LinkedNode (Integer key, Integer value, LinkedNode prev, LinkedNode next) {
this.key = key;
this.value = value;
this.prev = prev;
this.next = next;
}
}
private Integer capacity;
private LinkedNode head;
private LinkedNode tail;
private Map<Integer, LinkedNode> cache = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
this.tail = new LinkedNode();
this.head = new LinkedNode();
tail.prev = head;
head.next = tail;
}
public int get(int key) {
if (cache.get(key) == null) {
return -1;
}
LinkedNode node = cache.get(key);
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
LinkedNode node = cache.get(key);
node.value = value;
moveToHead(node);
return;
}
if (cache.size() >= capacity) {
LinkedNode node = removeTail();
cache.remove(node.key);
}
LinkedNode node = new LinkedNode(key, value);
addToHead(node);
cache.put(key, node);
}
private void removeNode(LinkedNode node) {
node.next.prev = node.prev;
node.prev.next = node.next;
}
private void moveToHead(LinkedNode node) {
removeNode(node);
addToHead(node);
}
private void addToHead(LinkedNode node) {
head.next.prev = node;
node.next = head.next;
head.next = node;
node.prev = head;
}
private LinkedNode removeTail() {
LinkedNode res = tail.prev;
removeNode(res);
return res;
}
}
/**
* 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);
*/