-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_replacement.cpp
40 lines (35 loc) · 1.18 KB
/
cache_replacement.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
#include <list>
#include <unordered_map>
using namespace std;
//https://leetcode-cn.com/problems/lru-cache-lcci/
class LRUCache {
using iter = list<pair<int, int>>::iterator;
list<pair<int, int>> doubly_list;
unordered_map<int, iter> hash_map;
int cap;
public:
explicit LRUCache(int capacity) : cap(capacity) {
}
optional<int> get(int key) {
if (hash_map.find(key) == hash_map.end()) return std::nullopt;
doubly_list.push_front(std::move(*hash_map[key]));
doubly_list.erase(hash_map[key]);
hash_map[key] = doubly_list.begin();
return hash_map[key]->second;
}
void put(int key, int value) {
if (hash_map.find(key) == hash_map.end()) {
doubly_list.emplace_front(key, value);
hash_map[key] = doubly_list.begin();
if (hash_map.size() > cap) {
hash_map.erase(doubly_list.back().first);
doubly_list.pop_back();
}
} else {
doubly_list.push_front(std::move(*hash_map[key]));
doubly_list.erase(hash_map[key]);
hash_map[key] = doubly_list.begin();
hash_map[key]->second = value;
}
}
};