您的位置:首页 > 其它

LRU Cache -- LeetCode

2016-01-28 12:45 323 查看
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.

思路:使用哈希表来记录key与值。为了实现LRU,我们需要实现一个双向链表,最少使用的在链表头,最近使用的在链表尾。对于每一个key,我们还需要一个哈希表来记录它在该链表中的地址。

在代码实现过程中,新申请一个链表只能用new的形式来申请,该语句将返回一个申请后的指针。

class LRUCache{
public:
class dlist
{
public:
dlist *pre, *next;
int key;
dlist(int d, dlist *p, dlist *f) : key(d), pre(p), next(f){}
};
int cap;
dlist *front, *tail;
unordered_map<int, int> data;
unordered_map<int, dlist *> addr;
LRUCache(int capacity) {
cap = capacity;
front = new dlist(0, NULL, NULL);
tail = new dlist(0, NULL, NULL);
front->next = tail;
tail->pre = front;
}

int get(int key) {
if (data.count(key) == 0) return -1;
Delete(addr[key]);
AddtoTail(addr[key]);
return data[key];
}
void AddtoTail(dlist *node)
{
tail->pre->next = node;
node->pre = tail->pre;
node->next = tail;
tail->pre = node;
}
void Delete(dlist *node)
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
void set(int key, int value) {
if (data.size() == cap && data.count(key) == 0)
{
if (front->next == tail) return;
data.erase(front->next->key);
addr.erase(front->next->key);
Delete(front->next);
}
if (data.count(key) == 0)
{
data.insert(make_pair(key, value));
dlist *ent = new dlist(key, NULL, NULL);
addr.insert(make_pair(key, ent));
AddtoTail(ent);
}
else
{
data[key] = value;
Delete(addr[key]);
AddtoTail(addr[key]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: