-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
93 lines (69 loc) · 2.01 KB
/
Copy pathLRUCache.java
File metadata and controls
93 lines (69 loc) · 2.01 KB
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
90
91
92
93
package org.example;
import java.util.HashMap;
public class LRUCache {
private static class Node {
private int key;
private int value;
private Node pre;
private Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
pre = null;
next = null;
}
}
private int capacity = 0;
private final HashMap<Integer, Node> hashMap = new HashMap<>();
private final Node head = new Node(-1,-1);
private final Node tail = new Node(-1,-1);
public LRUCache(int capacity) {
this.capacity = capacity;
// 重要 一个优化的技巧
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if (!hashMap.containsKey(key)) {
return -1;
}
Node node = hashMap.get(key);
node.pre.next = node.next;
node.next.pre = node.pre;
Node preTail = tail.pre;
preTail.next = node;
node.pre = preTail;
node.next = tail;
tail.pre = node;
return node.value;
}
public void put(int key, int value) {
if (hashMap.containsKey(key)) {
Node node = hashMap.get(key);
node.value = value;
node.pre.next = node.next;
node.next.pre = node.pre;
Node preTail = tail.pre;
preTail.next = node;
node.pre = preTail;
node.next = tail;
tail.pre = node;
return;
}
// 到达容量限制 删除节点 更新指针head
if (hashMap.size() == capacity) {
Node t = head.next;
head.next = t.next;
t.next.pre = head;
hashMap.remove(t.key);
}
Node node = new Node(key, value);
// 插入到tail之前
Node preTail = tail.pre;
preTail.next = node;
node.pre = preTail;
node.next = tail;
tail.pre = node;
hashMap.put(key, node);
}
}