2
2
3
3
import java .util .HashMap ;
4
4
5
- public class LRU { // doublyLinkedList
6
- int key ;
7
- int val ;
8
- LRU next ;
9
- LRU prev ;
10
- }
5
+ /**
6
+ * Implementation of Least Recently Used (LRU) Cache
7
+ *
8
+ * Constructor:
9
+ * LRU(int capacity)
10
+ * Client methods:
11
+ * get(K key)
12
+ * put(K key, V value)
13
+ * Both methods above run in O(1) average time complexity
14
+ */
15
+ class LRU {
16
+ /**
17
+ * Helper node class that implements doubly linked list
18
+ */
19
+ private class doublyLinkedList {
20
+ private int key ;
21
+ private int val ;
22
+ private doublyLinkedList next ;
23
+ private doublyLinkedList prev ;
24
+ }
11
25
12
- class LRUCache {
13
- LRU dllHead ;
14
- LRU dllTail ;
15
- HashMap <Integer , LRU > keyToNode = new HashMap ();
16
- int capacity ;
17
- int lengthOfList = 0 ;
26
+ private doublyLinkedList dllHead ;
27
+ private doublyLinkedList dllTail ;
28
+ private HashMap <Integer , doublyLinkedList > keyToNode = new HashMap ();
29
+ private int capacity ;
30
+ private int lengthOfList = 0 ;
18
31
19
- public LRUCache (int capacity ) {
32
+ /**
33
+ * Constructs an instance of Least Recently Used Cache
34
+ *
35
+ * @param capacity the maximum capacity of the cache
36
+ */
37
+ public LRU (int capacity ) {
20
38
this .capacity = capacity ;
21
39
22
- dllHead = new LRU ();
40
+ dllHead = new doublyLinkedList ();
23
41
dllHead .key = -1 ;
24
42
dllHead .val = -1 ;
25
43
26
- dllTail = new LRU ();
44
+ dllTail = new doublyLinkedList ();
27
45
dllTail .key = -1 ;
28
46
dllTail .val = -1 ;
29
47
@@ -33,10 +51,17 @@ public LRUCache(int capacity) {
33
51
dllTail .next = null ;
34
52
}
35
53
54
+ /**
55
+ * Return the value of the key if it exists or return null
56
+ *
57
+ * @param key key of the value to be obtained from LRU cache
58
+ */
36
59
public int get (int key ) {
37
- if (!keyToNode .containsKey (key )) return -1 ;
38
-
39
- LRU temp = keyToNode .get (key );
60
+ if (!keyToNode .containsKey (key )) {
61
+ return -1 ;
62
+ }
63
+
64
+ doublyLinkedList temp = keyToNode .get (key );
40
65
temp .prev .next = temp .next ;
41
66
temp .next .prev = temp .prev ;
42
67
@@ -48,13 +73,19 @@ public int get(int key) {
48
73
return keyToNode .get (key ).val ;
49
74
}
50
75
76
+ /**
77
+ * Insert key-value pair to LRU cache
78
+ *
79
+ * @param key key of the value to be inserted to LRU cache
80
+ * @param value value to be inserted to LRU cache
81
+ */
51
82
public void put (int key , int value ) {
52
83
boolean addingNewNode = true ;
53
84
54
- LRU newlyCached ;
85
+ doublyLinkedList newlyCached ;
55
86
56
87
if (!keyToNode .containsKey (key )) {
57
- newlyCached = new LRU ();
88
+ newlyCached = new doublyLinkedList ();
58
89
newlyCached .key = key ;
59
90
newlyCached .val = value ;
60
91
keyToNode .put (key , newlyCached );
0 commit comments