-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathLRU_Cache.cpp
50 lines (41 loc) · 1.15 KB
/
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
44
45
46
47
48
49
50
// Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
struct Node {
int key;
int value;
Node(int key, int value) : key(key), value(value) {}
};
class LRUCache {
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
if (!keyToIterator.count(key))
return -1;
const auto& it = keyToIterator[key];
// move it to the front
cache.splice(begin(cache), cache, it);
return it->value;
}
void put(int key, int value) {
// no capacity issue, just update the value
if (keyToIterator.count(key)) {
const auto& it = keyToIterator[key];
// move it to the front
cache.splice(begin(cache), cache, it);
it->value = value;
return;
}
// check the capacity
if (cache.size() == capacity) {
const auto& lastNode = cache.back();
// that's why we store `key` in `Node`
keyToIterator.erase(lastNode.key);
cache.pop_back();
}
cache.emplace_front(key, value);
keyToIterator[key] = begin(cache);
}
private:
const int capacity;
list<Node> cache;
unordered_map<int, list<Node>::iterator> keyToIterator;
};