forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
lru-cache.cpp
94 lines (81 loc) · 2.35 KB
/
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
#include <list>
class LRUCache {
public:
LRUCache(int capacity) : capa_(capacity) {
}
int get(int key) {
if (!map_.count(key)) {
return -1;
}
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
}
void put(int key, int value) {
if (capa_ <= 0) {
return;
}
// If cache is full while inserting, remove the last one.
if (!map_.count(key) && list_.size() == capa_) {
auto del = list_.front(); list_.pop_front();
map_.erase(del.first);
}
update(key, value);
}
private:
list<pair<int, int>> list_; // key, value
unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
int capa_;
// Update (key, iterator of (key, value)) pair
void update(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
list_.erase(it->second);
}
list_.emplace_back(key, value);
map_[key] = prev(end(list_));
}
};
// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
class LRUCache2 {
public:
LRUCache2(int capacity) : capa_(capacity) {
}
int get(int key) {
if (!map_.count(key)) {
return -1;
}
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
}
void put(int key, int value) {
if (capa_ <= 0) {
return;
}
// If cache is full while inserting, remove the last one.
if (!map_.count(key) && list_.size() == capa_) {
auto del = list_.back(); list_.pop_back();
map_.erase(del.first);
}
update(key, value);
}
private:
list<pair<int, int>> list_; // key, value
unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
int capa_;
// Update (key, iterator of (key, value)) pair
void update(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
list_.erase(it->second);
}
list_.emplace_front(key, value);
map_[key] = list_.begin();
}
};