-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru-cache.cpp
39 lines (37 loc) · 1.06 KB
/
lru-cache.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
class LRUCache{
public:
int capacity;
map<int, int> time2key; // time : key
unordered_map<int, int> key2value; // key : value
unordered_map<int, int> key2time; // key : time
int id = 0;
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (key2value.count(key) > 0){
time2key.erase(key2time[key]);
key2time[key] = id;
time2key[id] = key;
id++;
return key2value[key];
}
else{
return -1;
}
}
void set(int key, int value) {
if (key2value.count(key) == 0 && capacity == key2value.size()){
key2value.erase(time2key.begin()->second);
key2time.erase(time2key.begin()->second);
time2key.erase(time2key.begin());
}
if (key2value.count(key) > 0){
time2key.erase(key2time[key]);
}
key2value[key] = value;
time2key[id] = key;
key2time[key] = id;
id++;
}
};