Note:
就是模拟一下每个操作的过程,每次插入或者读取一个之后,就把这个数据放到头,然后put的时候如果超过了size,就给末尾的元素删除掉就好了
代码如下:
class LRUCache {
public:
struct Node {
int key, value;
Node* left;
Node* right;
Node(): key(0), value(0), left(nullptr), right(nullptr) {}
Node(int _key, int _value): key(_key), value(_value), left(nullptr), right(nullptr) {}
}*L, *R;
int n;
unordered_map<int, Node*> hash;
void insert(Node* p){
p -> right = L -> right;
p -> left = L;
L -> right -> left = p;
L -> right = p;
}
void remove(Node* p){
p -> right -> left = p -> left;
p -> left -> right = p -> right;
}
LRUCache(int capacity) {
n = capacity;
L = new Node(-1, -1), R = new Node(-1, -1);
L -> right = R;
R -> left = L;
}
int get(int key) {
if(hash.count(key) == 0) return -1;
auto p = hash[key];
remove(p);
insert(p);
return p -> value;
}
void put(int key, int value) {
if(hash.count(key)){
auto p = hash[key];
p -> value = value;
remove(p);
insert(p);
}else {
if(hash.size() == n){
auto p = R -> left;
remove(p);
hash.erase(p -> key);
delete p;
}
auto p = new Node(key, value);
hash[key] = p;
insert(p);
}
}
};
/**
* 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);
*/