-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq1lrucache.cpp
More file actions
37 lines (31 loc) · 879 Bytes
/
Copy pathq1lrucache.cpp
File metadata and controls
37 lines (31 loc) · 879 Bytes
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
#include <unordered_map>
#include <list>
class LRUCache {
public:
LRUCache(int capacity) : cap(capacity) {}
int get(int key) {
auto it = mp.find(key);
if (it == mp.end()) return -1;
lst.splice(lst.begin(), lst, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = mp.find(key);
if (it != mp.end()) {
it->second->second = value;
lst.splice(lst.begin(), lst, it->second);
return;
}
if (lst.size() == cap) {
int oldKey = lst.back().first;
mp.erase(oldKey);
lst.pop_back();
}
lst.push_front({key, value});
mp[key] = lst.begin();
}
private:
int cap;
std::list<std::pair<int,int>> lst;
std::unordered_map<int, std::list<std::pair<int,int>>::iterator> mp;
};