题目
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.
Subscribe to see which companies asked this question
解题思路
数据结构:双向链表,map
用map存储每次加入和更改的节点信息,这样可以保证在O(1)的时间get到key。
每次被访问或者新加入的节点放到链表尾,当超过最大数目时,从链表头部淘汰。
代码
struct Node{
int key;
int val;
Node *prev;
Node *next;
Node(int key, int val): key(key), val(val), prev(NULL), next(NULL) {}
};
class LRUCache{
public:
Node *head;
Node *tail;
map<int, Node*> m;
int max_cap;
int cur_cap;
void move2tail(Node *node){
//如果cache hit,先删除
if (NULL != m[node->key]){
node->prev->next = node->next;
node->next->prev = node->prev;
}
//再添加到链表尾
node->prev = tail->prev;
node->next = tail;
tail->prev->next = node;
tail->prev = node;
}
LRUCache(int capacity) {
//这里定义了链表头和尾,也可以不要
head = new Node(-1, -1);
tail = new Node(-1, -1);
head->next = tail;
tail->prev = head;
max_cap = capacity;
cur_cap = 0;
}
int get(int key) {
//cache miss
if (NULL == m[key])
return -1;
//cache hit
Node *node = m[key];
move2tail(node);
return node->val;
}
void set(int key, int value) {
if (NULL == m[key]){
if (cur_cap == max_cap)
{
m[head->next->key] = NULL;
//删除第一个结点,也就是head->next
Node *prev = head->next->prev;
Node *next = head->next->next;
prev->next = next;
next->prev = prev;
}
//新增一个节点,并添加到链表尾
Node *node = new Node(key, value);
move2tail(node);
m[key] = node;//更新map
if(cur_cap < max_cap)
cur_cap++;
}
else
{
Node *node = m[key];
node->val = value;
move2tail(node);
}
}
};
参考资料
语言 | 链接 |
---|---|
c++ | http://www.cnblogs.com/ganganloveu/p/4108979.html |
java | http://www.cnblogs.com/yrbbest/p/4489577.html |
python | http://www.jianshu.com/p/32e38137ec50 |