请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache
类:
LRUCache(int capacity)
以 正整数 作为容量 capacity
初始化 LRU 缓存int get(int key)
如果关键字 key
存在于缓存中,则返回关键字的值,否则返回 -1
。void put(int key, int value)
如果关键字 key
已经存在,则变更其数据值 value
;如果不存在,则向缓存中插入该组 key-value
。如果插入操作导致关键字数量超过 capacity
,则应该 逐出 最久未使用的关键字。函数 get
和 put
必须以 O(1)
的平均时间复杂度运行。
示例:
输入 ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] 输出 [null, null, null, 1, null, -1, null, -1, 3, 4] 解释 LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // 缓存是 {1=1} lRUCache.put(2, 2); // 缓存是 {1=1, 2=2} lRUCache.get(1); // 返回 1 lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} lRUCache.get(2); // 返回 -1 (未找到) lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} lRUCache.get(1); // 返回 -1 (未找到) lRUCache.get(3); // 返回 3 lRUCache.get(4); // 返回 4
get
和 put
必须以 O(1)
的平均时间复杂度运行。那就首先想到HashMap,还要面临顺序问题,数组和链表和树等等比较,显然要使用链表,因为使用的时候要升高顺序,无论是数组还是树等,复杂度都超过了O(n)。class LRUCache {
// 题目中需要创建一个HashMap来存储参数,因为题目要求复杂度为O(1),顺序就需要通过双向链表的节点实现
// 构造双向链表节点
class Node {
int key;
int value;
Node prev;
Node next;
public Node() {}
public Node(int key,int value) {
this.key = key;
this.value = value;
}
}
private Node head, tail;
// 由于LRU,是最近使用,所以为了将使用后的节点放到最前面,还需要一个头尾节点。
private HashMap map;
// 容量大小
private Integer capacity;
// 现在的大小
private Integer nowCap;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
this.nowCap = 0;
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
// get算使用,头插入
Node node = map.get(key);
if (node == null) return -1;
// 查不到就实现节点的删除,然后头插入
node.prev.next = node.next;
node.next.prev = node.prev;
// 再头部插入
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
return node.value;
}
public void put(int key, int value) {
Node addNode = new Node(key, value);
// 当现在的大小没超过容器限度值,就可以put
Node temp = map.get(key);
if(this.nowCap < this.capacity) {
if (temp != null) {
// 删掉该元素
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
temp.value = value;
// 再从头部插入
temp.prev = head;
temp.next = head.next;
head.next.prev = temp;
head.next = temp;
map.put(key, temp);
} else {
// 再头部插入
addNode.prev = head;
addNode.next = head.next;
head.next.prev = addNode;
head.next = addNode;
// 并添加映射
map.put(key, addNode);
this.nowCap++;
}
} else {
// 超过限度值之后就要进行覆盖
// 先检查一些能不能查到
if (temp != null) {
// 删掉该元素
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
temp.value = value;
// 再从头部插入
temp.prev = head;
temp.next = head.next;
head.next.prev = temp;
head.next = temp;
map.put(key, temp);
} else {
// 删除map内的映射
map.remove(tail.prev.key);
// 查不到就找出末尾的删除,然后头插入
tail.prev.prev.next = tail.prev.next;
tail.prev.next.prev = tail.prev.prev;
// 再头部插入
addNode.prev = head;
addNode.next = head.next;
head.next.prev = addNode;
head.next = addNode;
// 并添加映射
map.put(key, addNode);
}
}
}
}