forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU Cache.java
More file actions
96 lines (72 loc) · 1.76 KB
/
LRU Cache.java
File metadata and controls
96 lines (72 loc) · 1.76 KB
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
class LRUCache {
Map<Integer, Node> map;
Node head, tail;
int capacity;
int count;
public LRUCache(int capacity) {
map = new HashMap<>();
this.capacity = capacity;
head = new Node();
head.previous = null;
tail = new Node();
tail.next = null;
head.next = tail;
tail.previous = head;
this.count = 0;
}
public int get(int key) {
Node node = map.get(key);
if (node == null) {
return -1;
}
moveToHead(node);
return node.val;
}
private void moveToHead(Node node) {
removeNode(node);
addNode(node);
}
private void addNode(Node node) {
node.previous = head;
node.next = head.next;
head.next.previous = node;
head.next = node;
}
private Node popTail() {
Node res = tail.previous;
removeNode(res);
return res;
}
private void removeNode(Node node) {
Node pre = node.previous;
Node post = node.next;
pre.next = post;
post.previous = pre;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node == null) {
Node newNode = new Node();
newNode.key = key;
newNode.val = value;
map.put(key, newNode);
addNode(newNode);
count++;
if (count > capacity) {
Node tail = popTail();
map.remove(tail.key);
count--;
}
}
else {
node.val = value;
moveToHead(node);
}
}
private class Node {
Node previous;
Node next;
int key;
int val;
}
}