-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLRU Cache.cpp
56 lines (52 loc) · 1.2 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
using namespace std;
class LRUCache
{
int maxsize = 0;
list<ii> order;
unordered_map<int, list<ii>::iterator> cache;
public:
LRUCache(int capacity)
{
// Complete function
maxsize = capacity;
order.clear();
cache.clear();
}
int get(int key)
{
// Complete function
if (cache.find(key) == cache.end())
{
return -1;
}
auto it = cache.find(key);
// int key = it->first;
int res = (*cache[key]).second;
order.erase(it->second);
order.push_front({key, res});
cache[key] = order.begin();
return res;
}
void put(int key, int value)
{
auto it = cache.find(key);
if (it != cache.end())
{
order.erase(it->second);
order.push_front({key, value});
cache[key] = order.begin();
}
else
{
order.push_front({key, value});
cache[key] = order.begin();
}
if (order.size() > maxsize)
{
int key = order.rbegin()->first;
order.pop_back();
cache.erase(key);
}
}
};