-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU Cache
95 lines (83 loc) · 1.78 KB
/
LRU Cache
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
94
95
import java.util.HashMap;
public class LRUCache {
private HashMap<Integer, DoubleLinkedListNode> map
= new HashMap<Integer, DoubleLinkedListNode>();
private DoubleLinkedListNode head;
private DoubleLinkedListNode end;
private int capacity;
private int len;
public LRUCache(int capacity) {
this.capacity = capacity;
len = 0;
}
public int get(int key) {
if (map.containsKey(key)) {
DoubleLinkedListNode latest = map.get(key);
removeNode(latest);
setHead(latest);
return latest.val;
} else {
return -1;
}
}
public void removeNode(DoubleLinkedListNode node) {
DoubleLinkedListNode cur = node;
DoubleLinkedListNode pre = cur.pre;
DoubleLinkedListNode post = cur.next;
if (pre != null) {
pre.next = post;
} else {
head = post;
}
if (post != null) {
post.pre = pre;
} else {
end = pre;
}
}
public void setHead(DoubleLinkedListNode node) {
node.next = head;
node.pre = null;
if (head != null) {
head.pre = node;
}
head = node;
if (end == null) {
end = node;
}
}
public void set(int key, int value) {
if (map.containsKey(key)) {
DoubleLinkedListNode oldNode = map.get(key);
oldNode.val = value;
removeNode(oldNode);
setHead(oldNode);
} else {
DoubleLinkedListNode newNode =
new DoubleLinkedListNode(key, value);
if (len < capacity) {
setHead(newNode);
map.put(key, newNode);
len++;
} else {
map.remove(end.key);
end = end.pre;
if (end != null) {
end.next = null;
}
setHead(newNode);
map.put(key, newNode);
}
}
}
}
class DoubleLinkedListNode {
public int val;
public int key;
public DoubleLinkedListNode pre;
public DoubleLinkedListNode next;
public DoubleLinkedListNode(int key, int value) {
val = value;
this.key = key;
}
}