-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU-Cache.cpp
More file actions
48 lines (43 loc) · 1.09 KB
/
Copy pathLRU-Cache.cpp
File metadata and controls
48 lines (43 loc) · 1.09 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
class LRUCache {
public:
int n;
list<int> dll;
unordered_map<int, pair<list<int>::iterator,int>> mpp;
LRUCache(int capacity) {
n = capacity;
}
void makeRecentlyUsed(int key){
dll.erase(mpp[key].first);
dll.push_front(key);
mpp[key].first = dll.begin();
}
int get(int key) {
if(mpp.find(key) == mpp.end()){
return -1;
}
makeRecentlyUsed(key);
return mpp[key].second;
}
void put(int key, int value) {
if(mpp.find(key) != mpp.end()){
mpp[key].second = value;
makeRecentlyUsed(key);
}else{
dll.push_front(key);
mpp[key] = {dll.begin(), value};
n--;
if(n < 0){
int keyToBeDeleted = dll.back();
mpp.erase(keyToBeDeleted);
dll.pop_back();
n++;
}
}
}
};
/**
* 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);
*/