-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.cpp
44 lines (40 loc) · 847 Bytes
/
LRUCache.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
class LRUCache{
public :
list<pair<int,int>> LRU;
unordered_map<int , list<pair<int,int>> :: iterator> mp;
int cap ;
LRUCache(){
}
LRUCache(int _cap){
cap = _cap;
}
int get(int key){
if(mp.find(key) == mp.end()) return -1;
else {
int value =(*mp[key]).second;
LRU.erase(mp[key]);
LRU.push_front({key,value});
mp[key] = LRU.begin();
return (*mp[key]).second;
}
}
void put(int key , int value){
if(mp.find(key) == mp.end()){
if(LRU.size() == cap){
int back = LRU.back().first;
LRU.erase(mp[back]);
mp.erase(back);
}
}
else
LRU.erase(mp[key]);
LRU.push_front({key , value});
mp[key] = LRU.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);
*/