描述:
LRU,在缓存中删除总是删除最近最少使用的key
思路分析:
1、缓存实现:查询、更新,一定是使用HashMap
2、通过链表来判断最近最少使用的是哪一个,即:最近有使用的放链表头、最近最少使用的放链表尾
3、因为需要删除链表中某个过期的节点,所以选择使用双向链表
4、HashMap中key就存查询搜索的key;value存放双向链表的节点
代码实现:
package com.qu;
import java.util.HashMap;
/**
* @title: LRUCache
* @description: 手写实现lru缓存、每次淘汰最近最少使用的
* @author:quLiangquan
* @date 2019/8/16 14:19
**/
class LRUCache {
private static class DLinkedNode {
int key;
int value;
DLinkedNode pre;
DLinkedNode next;
}
private HashMap<Integer, DLinkedNode> cache = new HashMap<>();
private int capacity;
private int count;
private DLinkedNode head, tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.count = 0;
this.head = new DLinkedNode();
this.tail = new DLinkedNode();
head.pre = null;
head.next = tail;
tail.pre = head;
tail.next = null;
}
//get过后,需要把get的节点从链表中更新至链表头
private void moveToHead(DLinkedNode node) {
removeNode(node);
addNode(node);
}
//把node从链表中移除
private void removeNode(DLinkedNode node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
//把node加到链表头上去
private void addNode(DLinkedNode node) {
node.pre = head;
node.next = head.next;
head.next = node;
node.next.pre = node;
}
//弹出最尾巴的节点
private void popTail() {
DLinkedNode res = tail.pre;
removeNode(res);
cache.remove(res.key); //注意一定要把map中对应的key删掉
}
public int get(int key) {
DLinkedNode node = cache.get(key);
if (node == null) {
return -1;
}
//获取之后,标记为最近使用的、node移动至链表头
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);
++count;
if (count > capacity) {
//超出容量了、把最后一个node弹出、并删除该noide、然后容量减一
popTail();
count--;
}
} else {
node.value = value;
moveToHead(node);
}
}
}