forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru-cache.cpp
45 lines (39 loc) · 1.18 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
// 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_.find(key) != map_.end()) {
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
} else {
return -1;
}
}
void put(int key, int value) {
// If cache is full while inserting, remove the last one.
if (map_.find(key) == map_.end() && 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();
}
};