-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0146.cpp
More file actions
37 lines (33 loc) · 911 Bytes
/
Copy path0146.cpp
File metadata and controls
37 lines (33 loc) · 911 Bytes
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
class LRUCache {
unordered_map<int, pair<int, int>> um;
queue<pair<int, int>> q;
int capacity;
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
auto it = um.find(key);
if (it == um.end()) return -1;
q.push({key, ++it->second.first});
return it->second.second;
}
void put(int key, int value) {
auto it = um.find(key);
if (it != um.end()) {
q.push({key, ++it->second.first});
it->second.second = value;
return;
}
if (um.size() == capacity) {
while (true) {
auto [key, time] = q.front();
q.pop();
if (um[key].first == time) {
um.erase(key);
break;
}
}
}
q.push({key, 0});
um[key] = {0, value};
}
};