-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU_cache.cpp
More file actions
54 lines (51 loc) · 1.21 KB
/
LRU_cache.cpp
File metadata and controls
54 lines (51 loc) · 1.21 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
struct Cache{
int key;
int value;
Cache(int k=0, int val = 0){
key = k;
value = val;
}
};
class LRUCache {
list<Cache> cache;
unordered_map<int, list<Cache>::iterator> ump;
int cap;
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
if(!ump.count(key))
return -1;
auto it = ump[key];
cache.push_front(*it);
cache.erase(it);
ump[key] = cache.begin();
return ump[key]->value;
}
void put(int key, int value) {
if(!ump.count(key)){
cache.push_front(Cache(key, value));
ump[key] = cache.begin();
if(cache.size()>cap){
auto last = cache.back();
ump.erase(last.key);
cache.pop_back();
}
}
else{
auto it = ump[key];
it->value = value;
cache.push_front(*it);
cache.erase(it);
ump[key] = cache.begin();
}
return;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/