-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146. LRU Cache.cpp
41 lines (40 loc) · 1.05 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
class LRUCache {
public:
list<pair<int,int>> l;
unordered_map<int,list<pair<int, int>>::iterator> m;
int size;
LRUCache(int capacity)
{
size=capacity;
}
int get(int key)
{
if(m.find(key)==m.end())
return -1;
l.splice(l.begin(),l,m[key]);
return m[key]->second;
}
void put(int key, int value)
{
if(m.find(key)!=m.end())
{
l.splice(l.begin(),l,m[key]);
m[key]->second=value;
return;
}
if(l.size()==size)
{
auto d_key=l.back().first;
l.pop_back();
m.erase(d_key);
}
l.push_front({key,value});
m[key]=l.begin();
}
};
/**
* 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);
*/