-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLRU_Cache.cpp
More file actions
54 lines (46 loc) · 1.05 KB
/
LRU_Cache.cpp
File metadata and controls
54 lines (46 loc) · 1.05 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
49
50
51
52
53
54
// https://leetcode.com/problems/lru-cache/
class LRUCache
{
int capacity;
list <int> recent;
unordered_map < int, int > cache;
unordered_map < int, list <int> ::iterator > pos;
void use(int key)
{
if(pos.count(key))
recent.erase(pos[key]);
else if(recent.size() >= capacity)
{
cache.erase(recent.back());
pos.erase(recent.back());
recent.pop_back();
}
recent.push_front(key);
pos[key] = recent.begin();
}
public:
LRUCache(int capacity)
{
this->capacity = capacity;
}
int get(int key)
{
if(cache.count(key))
{
use(key);
return cache[key];
}
return -1;
}
void put(int key, int value)
{
use(key);
cache[key] = value;
}
};
/**
* 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);
*/