请你设计并实现一个满足 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) 的平均时间复杂度运行。
分析
关注:
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
以O(1)的时间复杂度进行get和put,数据结构需采用双向链表+Map
自定义链表
初始化
- 易错点1:链表的引用关系,移除了链表的节点后,引用关系发生改变,map需要重新put新的引用节点
[x] 易错点2:链表的引用关系,移除了链表的节点后,引用关系发生改变,map需要重新put新的引用节点
class LRUCache {
DLink dLink;
Map<Integer,Node> map;
int cap;
public LRUCache(int capacity) {
dLink = new DLink();
map = new HashMap<>();
this.cap = capacity;
}
public int get(int key) {
if (map.containsKey(key)){
int val = map.get(key).val;
put(key,val);
return val;
}
return -1;
}
public void put(int key, int value) {
Node node = new Node(key,value);
if (map.containsKey(key)){
dLink.remove(map.get(key));
dLink.addHead(node);
map.put(key,node); //易错点1
}else {
if (map.size() == cap){
int oldKey = dLink.remove(dLink.tail.pre);
map.remove(oldKey);
}
map.put(key,node); //易错点2
dLink.addHead(node);
}
}
class Node {
int key;
int val;
Node next = null;
Node pre = null;
public Node(int key,int val) {
this.key = key;
this.val = val;
}
}
class DLink {
Node head;
Node tail;
public DLink() {
this.head = new Node(-1,-1);
this.tail = new Node(-1,-1);
head.next = tail;
tail.pre = head;
}
public void addHead(Node node){
node.next = head.next;
node.pre = head;
head.next.pre = node;
head.next = node;
}
public int remove(Node node){
node.pre.next = node.next;
node.next.pre = node.pre;
node.pre = null;
node.next = null;
return node.key;
}
}
}
易错点图示