-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU-Cache.cpp
More file actions
52 lines (44 loc) · 982 Bytes
/
LRU-Cache.cpp
File metadata and controls
52 lines (44 loc) · 982 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
46
47
48
49
50
51
52
class LRUCache
{
public:
unordered_map<int, int> key2value, key2count;
deque<int> que;
int _capacity, _size;
LRUCache(int capacity)
{
_capacity = capacity;
_size = 0;
}
int get(int key)
{
if (!key2count[key])
return -1;
else
{
que.push_back(key);
key2count[key]++;
return key2value[key];
};
}
void put(int key, int value)
{
_size += !key2count[key];
key2value[key] = value;
key2count[key]++;
que.push_back(key);
while (_size > _capacity)
{
int val = que.front();
que.pop_front();
key2count[val]--;
if (!key2count[val])
_size--;
};
};
};
/**
* 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);
*/