-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassLRUCache.cpp
49 lines (40 loc) · 891 Bytes
/
ClassLRUCache.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
class LRUCache
{
private:
map<int,int> m;
int cap;
list<int> q;
public:
LRUCache(int capacity)
{
// constructor for cache
cap = capacity;
}
int get(int key)
{
// this function should return value corresponding to key
if(m.find(key) == m.end()) return -1;
q.remove(key);
q.push_front(key);
return m[key];
}
void set(int key, int value)
{
// storing key, value pair
if(m.find(key) != m.end())
{
q.remove(key);
q.push_front(key);
m[key] = value;
return;
}
if(q.size() == cap)
{
int last = q.back();
q.pop_back();
m.erase(last);
}
m[key] = value;
q.push_front(key);
}
};