-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146_2.h
52 lines (44 loc) · 1.15 KB
/
146_2.h
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
//
// Created by 17336 on 2022/2/27.
//
#ifndef HOT100_146_2_H
#define HOT100_146_2_H
#include <list>
#include <unordered_map>
class LRUCache {
std::unordered_map<int, std::pair<int, std::list<int>::iterator>> map;
std::list<int> lst;
int cap;
public:
LRUCache(int capacity) : cap(capacity) {
}
int get(int key) {
if(!map.count(key)) return -1;
int value=map[key].first;
lst.erase(map[key].second);
map.erase(key);
map[key].first = value;
lst.push_front(key);
map[key].second = lst.begin();
return value;
}
void put(int key, int value) {
if (!map.count(key) && lst.size() >= cap) {
map.erase(lst.back());
lst.pop_back();
} else if(map.count(key)){
lst.erase(map[key].second);
map.erase(key);
}
map[key].first = value;
lst.push_front(key);
map[key].second = lst.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);
*/
#endif //HOT100_146_2_H