-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU Cache.cpp
More file actions
55 lines (50 loc) · 1.42 KB
/
LRU Cache.cpp
File metadata and controls
55 lines (50 loc) · 1.42 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
55
class LRUCache{
list<pair<int, int>> dq;
unordered_map<int, list<pair<int, int>>::iterator> um;
int capacity;
public:
LRUCache(int capacity) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
this->capacity = capacity;
}
int get(int key) {
if(um.find(key) == um.end())
return -1;
pair<int, int> temp = {um[key]->first, um[key]->second};
dq.erase(um[key]);
um.erase(key);
dq.push_front(temp);
um[key] = dq.begin();
return um[key]->second;
}
void put(int key, int value) {
if(dq.size() < capacity){
if(um.find(key) == um.end()){
dq.push_front({key, value});
um[key] = dq.begin();
}
else if(um.find(key) != um.end()){
dq.erase(um[key]);
um.erase(key);
dq.push_front({key, value});
um[key] = dq.begin();
}
}
else{
if(um.find(key) != um.end()){
dq.erase(um[key]);
um.erase(key);
dq.push_front({key, value});
um[key] = dq.begin();
}
else{
int temp = dq.back().first;
um.erase(temp);
dq.pop_back();
dq.push_front({key, value});
um[key] = dq.begin();
}
}
}
};