LeetCode 146. LRU 缓存

146. LRU 缓存

解题思路

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class LRUCache {

public class Node {
int key, val;
Node pre;
Node next;

public Node() {}

public Node(int _k, int _v) {
this.key = _k;
this.val = _v;
}
}

public class MyList {
Node head = new Node(0,0);
Node tail = new Node(0,0);

public MyList() {
head.next = tail;
tail.pre = head;
}

public void headInsert(Node node) {
node.next = head.next;
node.pre = head;
head.next.pre = node;
head.next = node;
}

public void remove(Node node) {
Node nodePre = node.pre;
Node nodeNext = node.next;
nodePre.next = nodeNext;
nodeNext.pre = nodePre;
}

public Node removeLast() {
Node nodeLast = tail.pre;
remove(nodeLast);
return nodeLast;
}
}

public int capacity;
public Map<Integer, Node> map;
public MyList myList;

public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
myList = new MyList();
}

public int get(int key) {
if(!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
myList.remove(node);
myList.headInsert(node);
return node.val;
}

public void put(int key, int value) {
// 存在
if(map.containsKey(key)) {
Node node = map.get(key);
node.val = value;
myList.remove(node);
myList.headInsert(node);
} else {
Node node = new Node(key, value);
if(map.size() == capacity) {
Node last = myList.removeLast();
map.remove(last.key);
}
myList.headInsert(node);
map.put(key, node);
}

}
}

LeetCode 146. LRU 缓存
https://sowink.cn/2026/02/08/LeetCode-146-LRU-缓存/
作者
Xurx
发布于
2026年2月8日
许可协议