146. LRU缓存机制
Posted xyqxyq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了146. LRU缓存机制相关的知识,希望对你有一定的参考价值。
LRU的思路:
? 查找某个节点,如果该节点存在,则将它放到头部
? 增加一个节点,如果不存在,将它添加到头部,如果此时超过了LRU的大小,则将最后一个节点删除;如果存在,就更新节点的value,然后放到头部。
实现方式可以用LinkedHashMap,也可以自己实现
LinkedHashMap:
class LRUCache extends LinkedHashMap<Integer,Integer> {
private int capacity;
public LRUCache(int capacity) {
super(capacity,0.75F,true);
this.capacity=capacity;
}
public int get(int key) {
return super.getOrDefault(key,-1);
}
public void put(int key, int value) {
super.put(key,value);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer,Integer> eldest) {
return size()>capacity;
}
}
/**
* 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);
*/
手动实现 hash + 链表
import java.util.Hashtable;
class LRUCache {
class DLinkedNode {
int key;
int value;
DLinkedNode prev;
DLinkedNode next;
}
private Hashtable<Integer, DLinkedNode> cache = new Hashtable<Integer, DLinkedNode>();
private int size;
private int capacity;
private DLinkedNode head, tail;
public LRUCache(int capacity) {
this.size=0;
this.capacity = capacity;
head = new DLinkedNode();
tail = new DLinkedNode();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DLinkedNode node = cache.get(key);
if (node == null) {
return -1;
}
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DLinkedNode node = cache.get(key);
if (node == null) {
DLinkedNode newNode = new DLinkedNode();
newNode.key = key;
newNode.value = value;
cache.put(key, newNode);
addNode(newNode);
++size;
if (size>capacity) {
DLinkedNode _tail = popTail();
cache.remove(_tail.key);
--size;
}
} else {
node.value = value;
moveToHead(node);
}
}
private void addNode(DLinkedNode node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(DLinkedNode node) {
node.next.prev = node.prev;
node.prev.next = node.next;
}
private void moveToHead(DLinkedNode node) {
removeNode(node);
addNode(node);
}
private DLinkedNode popTail() {
DLinkedNode 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);
*/
以上是关于146. LRU缓存机制的主要内容,如果未能解决你的问题,请参考以下文章