-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlRUCache.cpp
More file actions
40 lines (36 loc) · 1.01 KB
/
lRUCache.cpp
File metadata and controls
40 lines (36 loc) · 1.01 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
// Source: https://leetcode.com/problems/lru-cache/
// Author: Miao Zhang
// Date: 2021-01-22
class LRUCache {
private:
int capacity_;
list<pair<int, int>> cache_;
unordered_map<int, list<pair<int, int>>::iterator> m_;
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
const auto it = m_.find(key);
if (it == m_.cend()) {
return -1;
}
cache_.splice(cache_.begin(), cache_, it->second);
return it->second->second;
}
void put(int key, int value) {
const auto it = m_.find(key);
if (it != m_.cend()) {
it->second->second = value;
cache_.splice(cache_.begin(), cache_, it->second);
return;
}
if (cache_.size() == capacity_) {
const auto& node = cache_.back();
m_.erase(node.first);
cache_.pop_back();
}
cache_.emplace_front(key, value);
m_[key] = cache_.begin();
}
};