看了很久才知道是什么意思......
哈希表+双向链表,注意哈希表存放的对应关系是key和链表节点的,而链表节点存储value。
注意一下链表需要设置头尾指针。
cpp
class LRUCache {
public:
struct ListNode{
int key,val;
ListNode* next;
ListNode* prev;
ListNode():key(0),val(0),next(nullptr),prev(nullptr){}
ListNode(int key,int value,ListNode* next=nullptr,ListNode* prev=nullptr):key(key),val(value),next(next),prev(prev){}
};
ListNode* head;
ListNode* tail;
int capacity;
unordered_map<int,ListNode*> hash;
LRUCache(int capacity) {
this->capacity=capacity;
head=new ListNode();
tail=new ListNode(0,0,nullptr,head);
head->next=tail;
}
int get(int key) {
if(hash.find(key)==hash.end()) return -1;
ListNode* g=hash[key];
g->next->prev=g->prev;
g->prev->next=g->next;
head->next->prev=g;
g->next=head->next;
g->prev=head;
head->next=g;
return g->val;
}
void put(int key, int value) {
if(hash.find(key)!=hash.end()){
hash[key]->val=value;
int k=get(key);
return;
}
if(capacity>0) capacity--;
else{
ListNode* t=tail->prev;
tail->prev=tail->prev->prev;
tail->prev->next=tail;
hash.erase(t->key);
}
ListNode* n=new ListNode(key,value,head->next,nullptr);
head->next->prev=n;
n->prev=head;
head->next=n;
hash[key]=n;
}
};
/**
* 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);
*/