-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathLRUCache.java
85 lines (67 loc) · 1.72 KB
/
LRUCache.java
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
package leetcode.datastructure;
import java.util.HashMap;
public class LRUCache {
static class Node {
int key;
int value;
Node pre;
Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
HashMap<Integer, Node> map;
Node sentinel;
int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
sentinel = new Node(-1, -1);
sentinel.next = sentinel;
sentinel.pre = sentinel;
this.map = new HashMap<>(capacity);
}
public int get(int key) {
if (map.containsKey(key)) {
Node node = map.get(key);
cutOriginalLink(node);
insertToHead(node);
return node.value;
}
return -1;
}
public void put(int key, int value) {
Node node;
if (map.containsKey(key)) {
node = map.get(key);
node.value = value;
cutOriginalLink(node);
} else {
node = new Node(key, value);
if (map.size() == capacity) {
Node tail = sentinel.pre;
// 去掉尾巴
map.remove(tail.key);
cutOriginalLink(tail);
}
map.put(key, node);
}
insertToHead(node);
}
/**
* 断开原来的链接
*/
private void cutOriginalLink(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
/**
* 插入到头
*/
private void insertToHead(Node node) {
node.next = sentinel.next;
sentinel.next.pre = node;
node.pre = sentinel;
sentinel.next = node;
}
}