forked from Anchor89/LeetCodeAnchor89
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRUCache.cpp
42 lines (37 loc) · 937 Bytes
/
LRUCache.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
#include "LeetCode.h"
class LRUCache{
public:
using Container = list<pair<int, int>>;
using ContainerPtr = Container::iterator;
using Index = unordered_map<int, ContainerPtr>;
Container container;
Index index;
int capacity;
LRUCache(int capacity_) {
capacity = capacity_;
}
int get(int key) {
int result = -1;
if (index.count(key) > 0) {
result = index[key]->second;
set(key, result);
}
return result;
}
void set(int key, int value) {
if (index.count(key) > 0) {
container.erase(index[key]);
container.push_front(make_pair(key,value));
index[key] = container.begin();
} else {
container.push_front(make_pair(key, value));
index[key] = container.begin();
while (container.size() > capacity) {
index.erase(container.back().first);
auto last = container.end();
last--;
container.erase(last);
}
}
}
};