-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache
82 lines (70 loc) · 1.96 KB
/
146. 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
class LRUCache {
private final int capacity;
private final HashMap<Integer, Node> map;
private final DoublyLinkedList cache;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.cache = new DoublyLinkedList();
}
public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
cache.moveToHead(node);
return node.value;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
cache.moveToHead(node);
} else {
if (map.size() >= capacity) {
Node tail = cache.removeTail();
map.remove(tail.key);
}
Node newNode = new Node(key, value);
map.put(key, newNode);
cache.addToHead(newNode);
}
}
private static class Node {
int key, value;
Node prev, next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private static class DoublyLinkedList {
private final Node head;
private final Node tail;
DoublyLinkedList() {
head = new Node(0, 0);
tail = new Node(0, 0);
head.next = tail;
tail.prev = head;
}
void addToHead(Node node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
void removeNode(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
void moveToHead(Node node) {
removeNode(node);
addToHead(node);
}
Node removeTail() {
Node tailPrev = tail.prev;
removeNode(tailPrev);
return tailPrev;
}
}
}