-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache.java
100 lines (79 loc) · 2.04 KB
/
146. 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class LRUCache {
class Node{
int key;
int value;
Node prev;
Node next;
}
private void addNode(Node node) // add first
{
Node nbr = head.next;
node.next = nbr;
node.prev = head;
nbr.prev = node;
head.next = node;
}
private void removeNode(Node node)
{
Node prevNbr = node.prev;
Node nextNbr = node.next;
prevNbr.next = nextNbr;
nextNbr.prev = prevNbr;
node.next = node.prev = null;
}
private void moveToFront(Node node)
{
removeNode(node);
addNode(node);
}
HashMap<Integer, Node> cache;
int cap;
Node head, tail;
public LRUCache(int capacity) {
cache = new HashMap<>();
cap = capacity;
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
Node node = cache.get(key);
if(node == null)
return -1;
else
{
int val = node.value;
moveToFront(node);
return val;
}
}
public void put(int key, int value) {
Node node = cache.get(key);
if(node == null) // pair doesn't exist in the cache
{
Node newNode = new Node();
newNode.key = key;
newNode.value = value;
if(cache.size() == cap)
{
Node LRU_Node = tail.prev;
cache.remove(LRU_Node.key);
removeNode(LRU_Node);
}
cache.put(key, newNode);
addNode(newNode);
}
else
{
node.value = value;
moveToFront(node); // make recently used
}
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/