LRU Cache LeetCode solution in Python

1
class LRUCache {
2
int N;
3
list<int> pages;
4
unordered_map<int, pair<int, list<int>::iterator>> cache;
5
public:
6
LRUCache(int capacity) : N(capacity) {
7

8
}
9

10
int get(int key) {
11
if (cache.find(key) != cache.end()) {
12
pages.erase(cache[key].second);
13
pages.push_front(key);
14
cache[key].second = pages.begin();
15
return cache[key].first;
16
}
17

18
return -1;
19
}
20

21
void put(int key, int value) {
22
if (cache.find(key) != cache.end()) {
23
pages.erase(cache[key].second);
24
} else {
25
if (pages.size() == N) {
26
int lru = pages.back();
27
cache.erase(lru);
28
pages.pop_back();
29
}
30
}
31

32
pages.push_front(key);
33
cache[key] = {value, pages.begin()};
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0