-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSolution.java
67 lines (59 loc) · 1.73 KB
/
Solution.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
// Using Doubly Linked List
class Node {
int key = 0, val = 0;
Node prev, next;
Node() {}
Node(int k, int v) {
key = k;
val = v;
}
}
class LRUCache {
Node head, tail;
HashMap<Integer, Node> map;
int maxCap;
public LRUCache(int capacity) {
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
maxCap = capacity;
map = new HashMap<>(maxCap);
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
removeAlreadyExistingNode(key);
updateRecentlyUsed(key, map.get(key).val);
return map.get(key).val;
}
public void put(int key, int value) {
if (map.containsKey(key))
removeAlreadyExistingNode(key);
else if (map.size() == maxCap) {
map.remove(tail.prev.key);
tail.prev.prev.next = tail;
tail.prev = tail.prev.prev;
}
updateRecentlyUsed(key, value);
}
private void removeAlreadyExistingNode(int key) {
Node existingNode = map.get(key);
existingNode.prev.next = existingNode.next;
existingNode.next.prev = existingNode.prev;
existingNode = null;
}
private void updateRecentlyUsed(int key, int value) {
Node newNode = new Node(key, value);
newNode.next = head.next; // (h)(new)->(t)
newNode.prev = head; // (h)<-(new)(t)
head.next = newNode; // (h)->(new)(t)
newNode.next.prev = newNode; // (h)(new)<-(t)
map.put(key, newNode);
}
}
/**
* 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);
*/