-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0146-lru-cache.cpp
79 lines (63 loc) · 1.98 KB
/
0146-lru-cache.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class LRUCache {
public:
LRUCache(int capacity): capacity(capacity) {}
int get(int key) {
if (!storage.count(key)) return -1;
auto itr = storage[key];
auto item = *itr;
dll.erase(itr);
dll.push_front(item);
storage[key] = dll.begin();
return item.second;
}
void put(int key, int value) {
if (storage.count(key)) {
auto itr = storage[key];
dll.erase(itr);
dll.emplace_front(key, value);
storage[key] = dll.begin();
return;
}
if (dll.size() == capacity) {
auto item = dll.back();
dll.pop_back();
storage.erase(item.first);
}
dll.emplace_front(key, value);
storage[key] = dll.begin();
}
private:
list<pair<int, int>> dll;
unordered_map<int, list<pair<int, int>>::iterator> storage;
int capacity;
};
// class LRUCache {
// int cap;
// list< pair<int, int> > holder;
// unordered_map<int, list< pair<int, int> >::iterator> indexMapper;
// public:
// LRUCache(int capacity) {
// cap = capacity;
// }
// int get(int key) {
// if (!indexMapper.count(key)) return -1;
// auto itr = *indexMapper[key];
// holder.erase(indexMapper[key]);
// holder.insert(holder.begin(), itr);
// indexMapper[key] = holder.begin();
// return itr.second;
// }
// void put(int key, int value) {
// if (get(key) != -1)
// indexMapper[key]->second = value;
// else {
// pair<int, int> item = {key, value};
// holder.insert(holder.begin(), item);
// indexMapper[key] = holder.begin();
// if (holder.size() > cap) {
// indexMapper.erase(holder.back().first);
// holder.pop_back();
// }
// }
// }
// };