LRU Cache LeetCode solution in Java

1
class LRUCache {
2
// Declare Node class for Doubly Linked List
3
class Node {
4
int key, value; // to store key and value
5
Node next, prev; // Next and Previous Pointers
6

7
Node(int k, int v) {
8
key = k;
9
value = v;
10
}
11
}
12

13
Node head = new Node(-1, -1); // Default values
14
Node tail = new Node(-1, -1);
15
Map<Integer, Node> mp; // to store key and Node
16
int cap;
17

18
public LRUCache(int capacity) {
19
// initializing in constructor
20
cap = capacity;
21
head.next = tail;
22
tail.prev = head;
23
mp = new HashMap<Integer, Node>();
24
}
25

26
public int get(int key) {
27
// if map contains the specific key
28
if (mp.containsKey(key)) {
29
Node existing = mp.get(key);
30
del(existing);
31
ins(existing); // reinserting to keep key after the head pointer and to update LRU list
32
return existing.value;
33
}
34
// otherwise
35
return -1;
36
}
37

38
public void put(int key, int value) {
39
// if map contains the key
40
if (mp.containsKey(key)) {
41
Node existing = mp.get(key);
42
// remove from the map and delete from the LRU list
43
mp.remove(key);
44
del(existing);
45
}
46
// if map size is equal to spcified capacity of the LRU list
47
if (mp.size() == cap) {
48
// remove from the map and delete from the LRU list
49
mp.remove(tail.prev.key);
50
del(tail.prev);
51
}
52
Node newNode = new Node(key, value);
53
ins(newNode);
54
mp.put(key, head.next);
55
}
56

57
public void ins(Node newNode) {
58
// Insert always after the head of the linkedList
59
Node temp = head.next;
60
head.next = newNode;
61
newNode.prev = head;
62
newNode.next = temp;
63
temp.prev = newNode;
64
}
65

66
public void del(Node newNode) {
67
// Remove the specified node using previous and next pointers
68
Node pr = newNode.prev;
69
Node nx = newNode.next;
70
pr.next = nx;
71
nx.prev = pr;
72
}
73
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0