#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
struct DLinkedNode{
int key, value;
DLinkedNode* prev;
DLinkedNode* next;
DLinkedNode(): key(0), value(0), prev(nullptr), next(nullptr) {}
DLinkedNode(int _key, int _value): key(_key), value(_value), prev(nullptr), next(nullptr){}
};
class LRUCache{
public:
LRUCache(int _capacity) : capacity(_capacity), size(0){
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = head;
}
int get(int key){
if(cache.count(key)==0) return -1;
DLinkedNode* node = cache[key];
movetohead(node);
return node->value;
}
void set(int key, int value){
if(cache.count(key)>0){
DLinkedNode* node = cache[key];
node->value = value;
movetohead(node);
}else{
if(size>=capacity){
DLinkedNode* node = removetail();
cache.erase(node->key);
--size;
delete node;
}
DLinkedNode* node = new DLinkedNode(key, value);
cache[key] = node;
addtohead(node);
++size;
}
}
void removeNode(DLinkedNode* node){
node->prev->next = node->next;
node->next->prev = node->prev;
}
void addtohead(DLinkedNode* node){
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
void movetohead(DLinkedNode* node){
removeNode(node);
addtohead(node);
}
DLinkedNode* removetail(){
DLinkedNode* node = tail->prev;
removeNode(node);
return node;
}
private:
unordered_map<int, DLinkedNode*> cache;
DLinkedNode* head;
DLinkedNode* tail;
int size;
int capacity;
};
int main(){
LRUCache lru(2);
vector<vector<int>> oper = {{1,1},{2,2},{1}, {3,3},{2}, {4,4},{1},{3},{4}};
for(auto op : oper){
if(op.size()==1){
int k = lru.get(op[0]);
cout<<k<<endl;
}else{
lru.set(op[0], op[1]);
cout<<"set:"<<op[0]<<endl;
}
}
}
|