Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
模拟LRU cache
主要用到了一个双向链表,模拟时间戳,head表示最早使用的,即即将被替换的,tail表示最新使用过的
如果新加入一个key,或者对某个key进行了set或者get操作,就将其放到队列尾部
将节点全部放入vector中,并且用一个map来维护key-index对。
如果某个key需要被替换,则先用map找到它所在的index,将这个index替换为新的节点,并且删除map中旧的key-index对,加入新的key-index对。
然后在双端队列中,将这个节点放到tail后面,并且将这个节点的前驱节点指向这个节点的后驱节点。
代码很丑陋。。。。
class LRUCache{
public:
int capacity;
struct DoubleNode{
int key;
int value;
DoubleNode* pre;
DoubleNode* next;
DoubleNode(int k,int v):key(k),value(v),pre(NULL),next(NULL){}
DoubleNode(){}
};
DoubleNode* head;
DoubleNode* tail;
map<int,int> key_index;
vector<DoubleNode*> nodes;
LRUCache(int capacity) {
this->capacity = capacity;
head = NULL;
tail=NULL;
}
int get(int key) {
map<int,int>::iterator it = key_index.find(key);
if(it==key_index.end())
return -1;
DoubleNode* node = nodes[it->second];
DoubleNode* p = node->pre;
if(nodes.size()==1 || node==tail)
return node->value;
if(node==head){
head = head->next;
head->pre = NULL;
node->next=NULL;
}else{
DoubleNode* n = node->next;
node->next=NULL;
node->pre=NULL;
p->next=n;
n->pre = p;
}
tail->next = node;
node->pre = tail;
tail = tail->next;
return node->value;
}
void set(int key, int value) {
map<int,int>::iterator it = key_index.find(key);
if(it==key_index.end()){
if(nodes.size()==capacity){
DoubleNode* node = head;
map<int,int>::iterator it = key_index.find(node->key);
int index = it->second;
key_index.erase(it);
head = head->next;
delete node;
node = new DoubleNode(key,value);
key_index.insert(pair<int,int>(key,index));
nodes[index] = node;
tail->next = node;
node->pre = tail;
tail = tail->next;
}else{
DoubleNode* node = new DoubleNode(key,value);
key_index.insert(pair<int,int>(key,nodes.size()));
nodes.push_back(node);
if(head==NULL){
head = node;
tail = node;
return;
}
tail->next = node;
node->pre = tail;
tail = node;
}
}else{
DoubleNode* node = nodes[it->second];
node->value = value;
DoubleNode* p = node->pre;
if(nodes.size()==1 || node==tail)
return;
if(node==head){
head = head->next;
head->pre = NULL;
node->next=NULL;
}else{
DoubleNode* n = node->next;
node->next=NULL;
node->pre=NULL;
p->next=n;
n->pre = p;
}
tail->next = node;
node->pre = tail;
tail = tail->next;
}
}
};