Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
这一道曾经在阿里的笔试中见过,真实惨痛的回忆。判断是否存在,最快的方法就是使用hash,但LRU在删除界面的时候需要进行判断找出最近最久未使用的页面。如果我们通过一个字段来记录该页面最近使用的时间,每次通过遍历列表来找到需要删除的页面,这样的操作复杂度为O(N)。还有更快的方法?网上看到一个十分有效的方法,使用双向列表来保存页面信息,当插入某个页面时,将其放在表头;当某个页面被查询后,将其移到表头;当页面已满,弹出表尾页面,该页面即为最近未使用的页面;所有这些操作的时间复杂度都为O(1),十分高效的实现。
代码如下:
class LRUCache {
public:
class ListNode
{
public:
int key;
int value;
ListNode* pre;
ListNode* next;
};
void addNode(ListNode* node)
{
node->next = head->next;
node->next->pre = node;
head->next = node;
node->pre = head;
}
void removeNode(ListNode* node)
{
ListNode *pre = node->pre;
ListNode *next = node->next;
pre->next = next;
next->pre = pre;
}
void moveToHead(ListNode* node)
{
removeNode(node);
addNode(node);
}
ListNode* popTail()
{
ListNode* node = tail->pre;
removeNode(node);
return node;
}
unordered_map<int,ListNode*> cache;
ListNode *head,*tail;
int capacity;
int count;
LRUCache(int _capacity) {
count = 0;
capacity = _capacity;
head = new ListNode();
head->pre = NULL;
tail = new ListNode();
tail->next = NULL;
head->next = tail;
tail->pre = head;
}
int get(int key) {
unordered_map<int,ListNode*>::iterator iter;
iter = cache.find(key);
if(iter == cache.end())
return -1;
moveToHead(cache[key]);
return cache[key]->value;
}
void put(int key, int value) {
unordered_map<int,ListNode*>::iterator iter;
iter = cache.find(key);
if(iter == cache.end())
{
ListNode* node = new ListNode();
node->key = key;
node->value = value;
cache.insert(unordered_map<int,ListNode*>::value_type(key,node));
addNode(node);
count++;
if(count > capacity)
{
node = popTail();
iter = cache.find(node->key);
cache.erase(iter);
count--;
}
}
else
{
cache[key]->value = value;
moveToHead(cache[key]);
}
}
};
/**
* 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);
*/