-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU Cache Code
89 lines (74 loc) · 1.82 KB
/
LRU Cache Code
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
class LRUCache {
public:
class node {
public:
int val;
int key;
node *prev;
node *next;
node(int _key,int _val)
{
this->val = _val;
this->key = _key;
}
};
int cap;
unordered_map<int, node*>mp;
node *head = new node(-1,-1);
node *tail = new node(-1,-1);
void addNode(node *newnode)
{
node *temp= head->next;
head->next = newnode;
newnode->prev= head;
newnode->next = temp;
temp->prev = newnode;
}
void deleteNode(node *delNode)
{
node *nextNode = delNode->next;
node *preNode = delNode->prev;
preNode->next = nextNode;
nextNode->prev = preNode;
}
LRUCache(int capacity) {
cap =capacity;
head->next=tail;
tail->prev=head;
}
int get(int key) {
if(mp.find(key)!=mp.end())
{
node *resnode = mp[key];
int res = resnode->val;
mp.erase(key);
deleteNode(resnode);
addNode(resnode);
mp[key]=tail;
return res;
}
return -1;
}
void put(int key, int value) {
if(mp.find(key)!=mp.end())
{
deleteNode(mp[key]);
mp.erase(key);
}
else if(mp.size()==cap)
{
mp.erase(tail->prev->key);
deleteNode(tail->prev);
}
node *newNode = new node(key,value);
addNode(newNode);
mp[key]=head->next;
return;
}
};
/**
* 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);
*/