forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlruCacheJava
62 lines (55 loc) · 1.23 KB
/
lruCacheJava
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
class LRUCache {
Node head = new Node(0, 0), tail = new Node(0, 0);
Map<Integer, Node> map = new HashMap();
int capacity;
public LRUCache(int _capacity) {
capacity = _capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if(map.containsKey(key)) {
Node node = map.get(key);
remove(node);
insert(node);
return node.value;
} else {
return -1;
}
}
public void put(int key, int value) {
if(map.containsKey(key)) {
remove(map.get(key));
}
if(map.size() == capacity) {
remove(tail.prev);
}
insert(new Node(key, value));
}
private void remove(Node node) {
map.remove(node.key);
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insert(Node node){
map.put(node.key, node);
node.next = head.next;
node.next.prev = node;
head.next = node;
node.prev = head;
}
class Node{
Node prev, next;
int key, value;
Node(int _key, int _value) {
key = _key;
value = _value;
}
}
}
/**
* 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);
*/