-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLRU-cache.cpp
51 lines (46 loc) · 1 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
51
#include <iostream>
#include <list>
#include <unordered_map>
using namespace std;
class LRUCache {
private:
int capacity;
list<int> recent;
unordered_map<int, int> cache;
unordered_map<int, list<int>::iterator> pos;
void use(int key) {
if (pos.find(key) != pos.end()) {
recent.erase(pos[key]);
} else if (recent.size() >= capacity) {
int old = recent.back();
recent.pop_back();
cache.erase(old);
pos.erase(old);
}
recent.push_front(key);
pos[key] = recent.begin();
}
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
if (cache.find(key) != cache.end()) {
use(key);
return cache[key];
}
return -1;
}
void set(int key, int value) {
use(key);
cache[key] = value;
}
};
int main(int argc, const char **argv) {
LRUCache *obj = new LRUCache(5);
for (int i = 0; i < 5; i++) {
obj->set(i, i );
}
for (int i = 0; i < 7; i++) {
std::cout << obj->get(i) << std::endl;
}
return 0;
}