-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLRU.cpp
43 lines (39 loc) · 993 Bytes
/
LRU.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
#inclue <list>
class LRUCache {
public:
struct LRUNode {
int value;
int key;
LRUNode(int k, int v) : key(k), value(v) {}
};
LRUCache(int capacity): cap(capacity) {}
int get(int key) {
if (!kv.count(key))
return -1;
move_front(key);
return values.front().value;
}
void set(int key, int value) {
if (!kv.count(key)) {
values.emplace_front(key, value);
kv[key] = values.begin();
if (values.size() > cap) {
kv.erase(values.back().key);
values.pop_back();
}
else {
kv[key]->value = value;
move_front(key);
}
}
}
private:
int move_front(int key) {
values.splice(values.begin(), values, kv[key]);
kv[key] = values.begin();
}
private:
int cap;
list<LRUNode> values;
unordered_map<int, list<LRUNode>::iterator> kv;
};