-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU Cache.cpp
More file actions
42 lines (37 loc) · 1.15 KB
/
LRU Cache.cpp
File metadata and controls
42 lines (37 loc) · 1.15 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
typedef struct _CacheNode {
int val;
int key;
_CacheNode(int key, int value):key(key), val(value) {}
} CacheNode;
class LRUCache{
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (cacheMap.find(key) != cacheMap.end()) {
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->val;
}
return -1;
}
void set(int key, int value) {
if (cacheMap.find(key) != cacheMap.end()) {
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
cacheMap[key]->val = value;
} else {
if (this->capacity == cacheList.size()) {
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front(CacheNode(key, value));
cacheMap[key] = cacheList.begin();
}
}
private:
int capacity;
list<CacheNode> cacheList;
unordered_map<int, list<CacheNode>::iterator> cacheMap;
};