-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146. LRU Cache (Leetcode)
42 lines (40 loc) · 1.11 KB
/
146. LRU Cache (Leetcode)
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
class LRUCache {
private:
int capacity;
list<pair<int, int>> List;
unordered_map<int, list<pair<int, int>>::iterator> Map;
public:
LRUCache(int capacity) {
this -> capacity = capacity;
}
int get(int key) {
if(Map.find(key) == Map.end())
return -1;
list<pair<int, int>>:: iterator iter = Map[key];
int value = (*iter).second;
List.erase(iter);
Map.erase(key);
List.push_back({key, value});
iter = List.end();
Map.insert({key, --iter});
return value;
}
void put(int key, int value) {
if(Map.find(key) == Map.end()) {
if(List.size() == capacity) {
Map.erase(List.front().first);
List.pop_front();
}
List.push_back({key, value});
auto iter = List.end();
Map.insert({key, --iter});
}
else {
List.erase(Map[key]);
Map.erase(key);
List.push_back({key, value});
auto iter = List.end();
Map.insert({key, --iter});
}
}
};