-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathLRUCache.java
89 lines (75 loc) · 1.97 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
86
87
88
89
// T: O(n)
// S: O(n)
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
private static class Node {
int key;
int value;
Node previous;
Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private final Map<Integer, Node> cache = new HashMap<>();
private final int capacity;
private Node head, tail;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (!cache.containsKey(key)) {
return -1;
}
final Node node = cache.get(key);
moveNodeToTail(node);
return node.value;
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
node.value = value;
moveNodeToTail(node);
} else if (cache.size() == capacity) {
Node node = new Node(key, value);
cache.put(key, node);
cache.remove(head.key);
appendToTail(node);
popHead();
} else {
Node node = new Node(key, value);
cache.put(key, node);
if (cache.size() == 1) {
head = node;
tail = node;
} else {
appendToTail(node);
}
}
}
private void moveNodeToTail(Node node) {
if (node == tail) {
return;
}
if (node == head) {
appendToTail(node);
popHead();
return;
}
Node previous = node.previous, next = node.next;
previous.next = next;
next.previous = previous;
appendToTail(node);
}
private void appendToTail(Node node) {
tail.next = node;
node.previous = tail;
tail = node;
}
private void popHead() {
head = head.next;
head.previous = null;
}
}