-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0146-lru-cache.java
79 lines (63 loc) · 1.72 KB
/
0146-lru-cache.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
class LRUCache {
private Map<Integer, Node> cache;
private int capacity;
private Node left;
private Node right;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new HashMap<>();
//left = LRU , right = most recent
this.left = new Node(0, 0);
this.right = new Node(0, 0);
this.left.next = this.right;
this.right.prev = this.left;
}
public int get(int key) {
if (cache.containsKey(key)) {
remove(cache.get(key));
insert(cache.get(key));
return cache.get(key).val;
} else {
return -1;
}
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
remove(cache.get(key));
}
cache.put(key, new Node(key, value));
insert(cache.get(key));
if (cache.size() > capacity) {
// remove from the list and delte the LRU from the hashmap
Node lru = this.left.next;
remove(lru);
cache.remove(lru.key);
}
}
// remove node from list
public void remove(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
}
// insert node at right
public void insert(Node node) {
Node prev = this.right.prev;
Node next = this.right;
prev.next = node;
next.prev = node;
node.next = next;
node.prev = prev;
}
private class Node {
private int key;
private int val;
Node next;
Node prev;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
}