-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146. LRU Cache
More file actions
79 lines (71 loc) · 1.64 KB
/
146. LRU Cache
File metadata and controls
79 lines (71 loc) · 1.64 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
class LRUCache {
//declare doubly linked list
Node head = new Node(0,0);
Node tail = new Node(0,0);
//declare HashMap
Map<Integer, Node> map = new HashMap();
int cap;
public LRUCache(int capacity)
{
cap = 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() == cap)
{
remove(tail.prev);
}
insert(new Node(key, value));
}
private void remove(Node node)
{
map.remove(node.key, node);
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insert(Node node)
{
map.put(node.key, node);
Node headNext=head.next;
head.next=node;
node.prev=head;
node.next=headNext;
headNext.prev=node;
}
class Node
{
Node prev, next; //reference pointers
int key, value;
Node(int key, int value) //constructor which takes the value and key
{
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);
*/