Use an unordered map and a doubly linked list to implement.
struct Node{
int key;
int value;
Node* next;
Node* pre;
Node(int k,int v){
key=k;
value=v;
pre=next=NULL;
}
};
class LRUCache{
public:
LRUCache(int capacity) {
cap=capacity;
cachesize=0;
head=new Node(0,0);
tail=new Node(0,0);
head->next=tail;
tail->pre=head;
}
int get(int key) {
if(mp.find(key)!=mp.end())
{
Node *p=mp[key];
p->next->pre=p->pre;
p->pre->next=p->next;
p->pre=tail->pre;
tail->pre->next=p;
p->next=tail;
tail->pre=p;
return mp[key]->value;
}
return -1;
}
void set(int key, int value) {
unordered_map<int,Node*>::iterator it=mp.find(key);
if(it!=mp.end())
{
Node *p=mp[key];
p->next->pre=p->pre;
p->pre->next=p->next;
p->value=value;
p->pre=tail->pre;
tail->pre->next=p;
p->next=tail;
tail->pre=p;
}
else
{
if(cachesize==cap)
{
it=mp.find(head->next->key);
Node *p=head->next;
head->next->next->pre=head;
head->next=head->next->next;
delete p;
mp.erase(it);
cachesize--;
}
Node *p=new Node(key,value);
p->pre=tail->pre;
tail->pre->next=p;
p->next=tail;
tail->pre=p;
mp.insert(make_pair(key,p));
cachesize++;
}
}
private:
unordered_map<int,Node*> mp;
Node* head;
Node* tail;
int cachesize;
int cap;
};