-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache.cpp
114 lines (95 loc) · 2.78 KB
/
146. LRU Cache.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// struct ListNode
// {
// int key;
// int value;
// ListNode* next = NULL;
// ListNode* prev = NULL;
// };
class LRUCache {
public:
class ListNode
{
public:
int key;
int value;
ListNode* prev = NULL;
ListNode* next = NULL;
};
ListNode* head = new ListNode();
ListNode* tail = new ListNode();
map<int,ListNode*> hashmap;
int cap;
LRUCache(int capacity)
{
head->next = tail;
tail->prev = head;
cap = capacity;
}
int get(int key)
{
if(hashmap.find(key)!=hashmap.end())
{
//Getting address of node to update
ListNode* toupdate = hashmap[key];
//Removing the node from its current pos
toupdate->prev->next = toupdate->next;
toupdate->next->prev = toupdate->prev;
//Adding it again to cache
ListNode* neighbour = head->next;
toupdate->next = neighbour;
neighbour->prev = toupdate;
head->next = toupdate;
toupdate->prev = head;
return hashmap[key]->value;
}
return -1;
}
void put(int key, int value)
{
//If it is already in cache
if(hashmap.find(key)!=hashmap.end() && hashmap.size()!=1)
{
//Getting address of node to update
ListNode* toupdate = hashmap[key];
//Removing the node from its current pos
toupdate->prev->next = toupdate->next;
toupdate->next->prev = toupdate->prev;
//Adding it again to cache
ListNode* neighbour = head->next;
toupdate->next = neighbour;
neighbour->prev = toupdate;
head->next = toupdate;
toupdate->prev = head;
toupdate->value = value;
}
else
{
//Creating the new node
ListNode* newnode = new ListNode();
newnode->key = key;
newnode->value = value;
//Adding new node to cache
ListNode* neighbour = head->next;
newnode->next = neighbour;
neighbour->prev = newnode;
head->next = newnode;
newnode->prev = head;
hashmap[key] = newnode;
//Checking if cache exceeds limit
if(hashmap.size()>cap)
{
//Removing Last Node
ListNode* toremove = tail->prev;
tail->prev = toremove->prev;
toremove->prev->next = tail;
hashmap.erase(toremove->key);
}
}
}
};
/**
* 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);
*/