-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlruLLCache.java
More file actions
66 lines (51 loc) · 1.28 KB
/
lruLLCache.java
File metadata and controls
66 lines (51 loc) · 1.28 KB
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
class LRUCache {
class Node {
int key, val;
Node prev, next;
Node(int k, int v) {
key = k;
val = v;
}
}
private Map<Integer, Node> map;
private int capacity;
private Node head, tail;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
head = new Node(0, 0);
tail = new Node(0, 0);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
remove(node);
insert(node);
return node.val;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
remove(map.get(key));
}
Node node = new Node(key, value);
insert(node);
map.put(key, node);
if (map.size() > capacity) {
Node lru = tail.prev;
remove(lru);
map.remove(lru.key);
}
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insert(Node node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
}