-
Notifications
You must be signed in to change notification settings - Fork 481
/
0146.cpp
36 lines (32 loc) · 865 Bytes
/
0146.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
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class LRUCache
{
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key)
{
if (cache.find(key) == cache.end()) return -1;
li.splice(li.begin(), li, cache[key]);
return cache[key]->second;
}
void put(int key, int value)
{
if (get(key) != -1)
{
cache[key]->second = value;
return;
}
if (cache.size() == capacity)
{
int delKey = li.back().first;
li.pop_back();
cache.erase(delKey);
}
li.emplace_front(key, value);
cache[key] = li.begin();
}
private:
int capacity;
list<pair<int, int>> li;
unordered_map<int, list<pair<int, int>>::iterator> cache;
};