-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
45 lines (39 loc) · 915 Bytes
/
Copy pathsolution.cpp
File metadata and controls
45 lines (39 loc) · 915 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
38
39
40
41
42
43
44
45
#include <unordered_map>
#include <list>
using namespace std;
class LRUCache
{
private:
int capacity;
list<int> order;
unordered_map<int, pair<int, list<int>::iterator>> cache;
public:
LRUCache(int capacity)
{
this->capacity = capacity;
}
int get(int key)
{
if (cache.find(key) == cache.end())
return -1;
order.erase(cache[key].second);
order.push_front(key);
cache[key].second = order.begin();
return cache[key].first;
}
void put(int key, int value)
{
if (cache.find(key) != cache.end())
{
order.erase(cache[key].second);
}
else if (cache.size() == capacity)
{
int lru = order.back();
order.pop_back();
cache.erase(lru);
}
order.push_front(key);
cache[key] = {value, order.begin()};
}
};