class Node
{
public:
int key_t;
int value_t;
Node(int key,int value):key_t(key),value_t(value)
{
}
};
class LRUCache {
public:
list<Node> cache;//缓存 双向链表 方便插入删除
unordered_map<int,list<Node>::iterator> m; //通过map方便查找节点位置 通过key找节点位置 前面是key 后面是双向链表当前位置的迭代器
int capacity;
LRUCache(int capacity) :capacity(capacity)
{
}
void output()
{
cout<<"cache=====cache"<<endl;
for(auto x=cache.begin();x!=cache.end();x++)
{
cout<<"key:"<<(*x).key_t<<" value:"<<(*x).value_t<<endl;
}
}
int get(int key)//get也算访问一次 放到前面
{
auto it=m.find(key);
if(it==m.end())//不存在
{
return -1;
}
else
{
if(cache.front().key_t!=key)
{
//map更新 只动链表
int val=(*m[key]).value_t;//暂时存储value
cache.erase(m[key]);
cache.emplace_front(Node(key,val));
m[key]=cache.begin();
}
return (*m[key]).value_t;
}
}
void put(int key, int value)
{
auto it=m.find(key);//首先先判断新的数据是否存在
if(it==m.cend())//新的数据不存在 放到双链表最前面
{
if(cache.size()>=capacity)//大于等于缓存容量 删掉尾巴
{
//注意顺序!!!!
/*
cache.pop_back();
m.erase(cache.back().key_t);
*/
m.erase(cache.back().key_t);
cache.pop_back();
}
//新数据直接放最前面
cache.emplace_front(Node(key,value));
m[key]=cache.begin();
}
else//如果存在数据已经存在
{
//如果链表开头 更新一下value 其他原封不动 反之 移到开头
if(cache.front().key_t!=key)
{
//map更新 只动链表
cache.erase(m[key]);
cache.emplace_front(Node(key,value));
m[key]=cache.begin();
}
else
{
auto cache_it=(*it).second;
(*cache_it).value_t=value;
}
}
}
};
/**
* 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);
*/
解法:用一个双链表存储数据,新的元素放在最前面,访问过一次也算用过,这样排在后面的都是最少用的,容量不够,删除之,key相同的需要更新value。
146. LRU Cache
Hard
251381FavoriteShare
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