-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146-lru-cache.cpp
More file actions
48 lines (43 loc) · 1.09 KB
/
0146-lru-cache.cpp
File metadata and controls
48 lines (43 loc) · 1.09 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
class LRUCache {
public:
unordered_map<int, int> cache;
unordered_map<int, int> key_to_time;
set<pair<int, int>> s; //(time, key) pairs
int t = 0;
int capacity;
LRUCache(int capacity) {
t = 0;
s.clear();
cache.clear();
this -> capacity = capacity;
}
void balance() {
if (cache.size() <= capacity) return;
auto [time, key_val] = *s.begin();
s.erase(s.begin());
key_to_time.erase(key_val);
cache.erase(key_val);
}
void update(int key) {
s.erase(make_pair(key_to_time[key], key));
s.insert(make_pair(t, key));
key_to_time[key] = t;
t++;
}
int get(int key) {
if (cache.find(key) == cache.end()) return -1;
update(key);
return cache[key];
}
void put(int key, int value) {
update(key);
cache[key] = value;
balance();
}
};
/**
* 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);
*/