-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLRU Cache
70 lines (61 loc) · 1.6 KB
/
LRU Cache
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
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) {
this.capacity=capacity;
head.next=tail;
tail.prev=head;
}
public int get(int key) {
if(map.containsKey(key)){
Node data=map.get(key);
//move data to the top
//remove the node
remove(data);
//insert it
insert(data);
return data.value;
}
return -1;
}
public void put(int key, int value) {
//if value is already present we move it to top
if(map.containsKey(key)){
remove(map.get(key));
}
//if cache is full
if(capacity == map.size()){
remove(tail.prev);
}
//tail.prev --> least recently used
insert(new Node (key,value));
}
void remove(Node node){
map.remove(node.key);
node.prev.next=node.next;
node.next.prev=node.prev;
}
void insert(Node node){
map.put(node.key,node);
Node headNext=head.next;
head.next=node;
node.prev=head;
headNext.prev=node;
node.next=headNext;
}
class Node{
Node prev,next;
int key,value;
Node (int key,int value){
this.key=key;
this.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);
*/