leetcode146. LRU缓存机制
2019-07-22 本文已影响0人
今天不想掉头发
image.png
双向链表+哈希表实现LRU
class LRUCache {
public static class LinkedNode {
int key;
int val;
LinkedNode prev;
LinkedNode next;
public LinkedNode(int key, int val) {
this.key = key;
this.val = val;
}
}
Map<Integer, LinkedNode> map;
LinkedNode head;
LinkedNode tail;
int capacity;
int count;
public LRUCache(int capacity) {
map = new HashMap<>();
head = new LinkedNode(0, 0);
tail = new LinkedNode(0, 0);
head.next = tail;
tail.prev = head;
this.capacity = capacity;
count = 0;
}
// 移除尾结点前面的节点
public void removeTail() {
if (tail.prev == head) throw new IllegalArgumentException("There is no node to remove");
LinkedNode node = tail.prev;
tail.prev.prev.next = tail;
tail.prev = tail.prev.prev;
}
// 将node节点添加到头结点后面
public void addToHead(LinkedNode node) {
node.next = head.next;
head.next.prev = node;
head.next = node;
node.prev = head;
}
// 删除node节点
public void removeNode(LinkedNode node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
public int get(int key) {
if (map.containsKey(key)) {
LinkedNode node = map.get(key);
removeNode(node);
addToHead(node);
return node.val;
}
return -1;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
LinkedNode node = map.get(key);
node.val = value;
removeNode(node);
addToHead(node);
} else {
LinkedNode node = new LinkedNode(key, value);
if (count == capacity) {
map.remove(tail.prev.key);
removeTail();
addToHead(node);
map.put(key, node);
} else {
addToHead(node);
map.put(key, node);
count++;
}
}
}
}
/**
* 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);
*/