LeetCode 146. LRU Cache LRU 缓存[Medium]

LeetCode 146 Java 版本题解及资料汇编。

题目

146. LRU 缓存 - 力扣(LeetCode)

LRU Cache - LeetCode

思路

哈希表 + 双向链表。

题解

题解1 基于 Java HashMap

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
85
86
87
88
89
class LRUCache {
Node head = new Node();
Node tail = new Node();
HashMap<Integer, Node> map = new HashMap<>();
int capacity;

public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}

public int get(int key) {
Node node = map.get(key);
if (node == null) {
return -1;
} else {
if (node.next != tail) {
moveToTail(node);
}

return node.value;
}
}

public void put(int key, int value) {
Node node = map.get(key);
if (node != null) {
node.value = value;
if (node.next != tail) {
moveToTail(node);
}
} else {
if (map.size() >= capacity) {
removeHead();
putInternal(key, value);
} else {
putInternal(key, value);
}
}
}

private void putInternal(int key, int value) {
Node node = new Node(key, value);
addNodeToTail(node);
map.put(key, node);
}

private void moveToTail(Node node) {
removeNode(node);
addNodeToTail(node);
}

private void removeNode(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;

node.prev = null;
node.next = null;
}

private void addNodeToTail(Node node) {
node.prev = tail.prev;
node.prev.next = node;
node.next = tail;
tail.prev = node;
}

private void removeHead() {
Node firstNode = head.next;
removeNode(head.next);
map.remove(firstNode.key);
}

private class Node {
private Node prev;
private Node next;
private int key;
private int value;

Node() {
}

Node(int key, int value) {
this.key = key;
this.value = value;
}
}
}

参考资料

  1. 官方题解:146. LRU 缓存 - 力扣(LeetCode)
  2. Labuladong题解:146. LRU 缓存 - 力扣(LeetCode)