-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146.cpp
More file actions
30 lines (27 loc) · 767 Bytes
/
0146.cpp
File metadata and controls
30 lines (27 loc) · 767 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
class LRUCache {
int capacity;
list<pair<int, int>> cacheList;
unordered_map<int, list<pair<int, int>>::iterator> cacheMap;
public:
LRUCache(int capacity) { this->capacity = capacity; }
int get(int key) {
if (cacheMap.find(key) == cacheMap.end())
return -1;
auto it = cacheMap[key];
cacheList.splice(cacheList.begin(), cacheList, it);
return it->second;
}
void put(int key, int value) {
if (cacheMap.find(key) != cacheMap.end()) {
auto it = cacheMap[key];
cacheList.erase(it);
}
cacheList.push_front({key, value});
cacheMap[key] = cacheList.begin();
if (cacheList.size() > capacity) {
auto last = cacheList.back();
cacheMap.erase(last.first);
cacheList.pop_back();
}
}
};