-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146-LRUCache.cpp
76 lines (67 loc) · 1.92 KB
/
146-LRUCache.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// NOTE
#include <typeinfo>
struct custom{
int key;
int value;
list<int>:: iterator loc;
};
class LRUCache {
public:
unordered_map<int, struct custom *> cache;
list<int> lst;
int filled;
int maxCapacity;
LRUCache(int capacity) {
maxCapacity = capacity;
filled = 0;
}
int get(int key) {
// Check cache for existence
// cout << "Looking for " << key << endl;
if(cache.find(key) == cache.end()) return -1;
else{
auto *it = cache[key];
int val = it->value;
// cout << it->loc;
lst.erase(it->loc);
lst.push_back(key);
// Update the cache
// cout << typeid(cache[key]).name();
// cout << typeid(lst.back()).name();
cache[key]->loc = (--lst.end());
// cout << "Found " << key << endl;
return val;
}
}
void put(int key, int value) {
// If filled, evict lru element
if(cache.find(key) == cache.end()){
if(filled == maxCapacity){
int k = *(lst.begin());
lst.erase(lst.begin());
cache.erase(k);
// cout << "Removing " << k << endl;
filled--;
}
}else{
list<int>:: iterator j = cache[key]->loc;
lst.erase(j);
cache.erase(key);
filled--;
}
lst.push_back(key);
struct custom *temp = (struct custom*)malloc(sizeof(struct custom));
temp->value = value;
temp->key = key;
temp->loc = (--lst.end());
cache[key] = temp;
filled++;
// cout << "Inserting " << key << ", " << value <<endl;
}
};
/**
* 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);
*/