-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomework02_LRU_cache.cpp
More file actions
43 lines (35 loc) · 1.13 KB
/
Homework02_LRU_cache.cpp
File metadata and controls
43 lines (35 loc) · 1.13 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
41
42
43
class LRUCache {
public:
list<pair<int,int>> cache;
unordered_map <int, list<pair<int,int>>::iterator> map;
int size = 0;
LRUCache(int capacity):size(capacity) {
}
//splice移动list的元素到另一个list某个位置
int get(int key) {
if(map.find(key) == map.end()) return -1;
cache.splice(cache.begin(),cache,map[key]);
return map[key]->second;
}
void put(int key, int value) {
if(map.find(key) != map.end()){
cache.splice(cache.begin(),cache,map[key]);
cache.begin()->second = value;
return;
//map[key] = list.begin();
}
if(cache.size() == size){
int key = cache.back().first;
cache.pop_back();
map.erase(key);
}
cache.push_front({key,value});
map[key] = cache.begin();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/