-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlru.cpp
More file actions
58 lines (52 loc) · 1.37 KB
/
lru.cpp
File metadata and controls
58 lines (52 loc) · 1.37 KB
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
52
53
54
55
56
57
58
#include <iostream>
#include <vector>
#include <unordered_map>
#include <list>
using namespace std;
class LRUCache{
private:
struct cacheNode{
int key;
int value;
cacheNode(int k, int v) : key(k), value(v){};
};
int capacity;
list<cacheNode> cacheList;
unordered_map<int, list<cacheNode>::iterator> cacheMap;
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if(cacheMap.find(key) == cacheMap.end()){
return -1;
}
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->value;
}
void set(int key, int value) {
if(cacheMap.find(key) == cacheMap.end()){
cacheList.push_front(cacheNode(key, value));
cacheMap[key] = cacheList.begin();
if(cacheList.size() > capacity){
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
}
else{
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}
};
int main(void){
LRUCache lru(1);
lru.set(2, 1);
cout << lru.get(2)<<endl;
lru.set(3, 2);
cout << lru.get(2)<<endl;
cout << lru.get(3)<<endl;
return 0;
}