-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU.h
More file actions
43 lines (39 loc) · 1.05 KB
/
LRU.h
File metadata and controls
43 lines (39 loc) · 1.05 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
//Least Recently Used (LRU) cache
class solution {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if(cacheMap.find(key) == cacheMap.end()) return -1;
//Transfers elements from x into the container, inserting them at position.
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()) {
if(cacheList.size() == capacity) {
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front(CacheNode(key, value));
cacheMap[key] = cacheList.begin();
}
else {
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList,cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}
private:
struct CacheNode {
int key;
int value;
CacheNode(int k, int value) : key(k), value(value){}
}
private:
std::list<CacheNode> cacheList;
std::unordered_map<int, std::list<CacheNode>::iterator> cacheMap;
int capacity;
}