-
Notifications
You must be signed in to change notification settings - Fork 765
/
Copy pathLRU_Cache.cpp
35 lines (33 loc) · 909 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
class LRUCache {
private:
int cap;
list<int> keys;
unordered_map<int, pair<int, list<int>::iterator>> cache;
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
if(cache.find(key) != cache.end()){
keys.erase(cache[key].second);
keys.push_front(key);
cache[key].second = keys.begin();
return cache[key].first;
}
return -1;
}
void put(int key, int value) {
if(cache.find(key) != cache.end()){
keys.erase(cache[key].second);
keys.push_front(key);
cache[key] = {value, keys.begin()};
}else{
if(keys.size() == cap){
cache.erase(keys.back());
keys.pop_back();
}
keys.push_front(key);
cache[key] = {value, keys.begin()};
}
}
};