-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU cache.cpp
43 lines (38 loc) · 978 Bytes
/
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
class LRUCache{
list<pair<int, int>> dq;
unordered_map<int, list<pair<int, int>>::iterator> um;
int cap;
public:
LRUCache(int cap) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
this->cap = cap;
}
int get(int key) {
if(um.find(key) == um.end())
return -1;
int value = um[key]->second;
dq.erase(um[key]);
um.erase(key);
dq.push_front({key, value});
um[key] = dq.begin();
return value;
}
void put(int key, int value) {
if(um.find(key) != um.end()){
dq.erase(um[key]);
um.erase(key);
}
if(dq.size() < cap){
dq.push_front({key, value});
um[key] = dq.begin();
}
else{
int temp = dq.back().first;
dq.erase(um[temp]);
um.erase(temp);
dq.push_front({key, value});
um[key] = dq.begin();
}
}
};