-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.java
120 lines (90 loc) · 2.02 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.HashMap;
import java.util.Map;
/*
* Implementation by Eric Xing
* LRU cache data structure with LinkedHashMap and Doubly-Linked list
* Implements the CACHE interface
* O(1) add, O(1) query
*/
public class LRUCache implements Cache {
// doubly linked node
static class Node {
int value;
Node prev;
Node next;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
// attributes
// max capacity
int capacity;
// current size
int size;
// head and tail of doubly-linked list
Node head;
Node tail;
// HashMap of all values
Map<Integer, Node> cache = new HashMap<>();
// Constructor
public LRUCache(int capacity) {
size = 0;
this.capacity = capacity;
head = new Node();
head.prev = null;
tail = new Node();
tail.next = null;
head.next = tail;
tail.prev = head;
}
// set the connections at the head to insert a new node
void add_at_head(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
// remove the node, by setting the next and prev
void remove(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
}
// remove the tail node
Node pop() {
Node res = tail.prev;
remove(res);
return res;
}
// query the key using the HashMap, and put it at the head (LRU)
public int get(int key) {
// O(1) HashMap query
if (cache.containsKey(key)) {
Node node = cache.get(key);
remove(node);
add_at_head(node);
return node.value;
}
// not found
return -1;
}
// insert a new value
public void add(int value) {
// made a new node for the value
Node newNode = new Node(value);
// insert it into the HashMap
cache.put(value, newNode);
// Make room if needed
if (size == capacity) {
Node last = pop();
cache.remove(last.value);
size--;
}
// insert it
add_at_head(newNode);
size++;
}
}