https://leetcode.com/problems/lru-cache/submissions/
https://www.cnblogs.com/grandyang/p/4587511.html
实现get和put
get,如果没有,返回-1;
如果有key,表明访问了一次,故将该key移到首部
put,将key放入容器,如果有,则应先删除;
如果大于容器的容量,将容器的尾部删除。
l.splice(l.begin(),l,it->second);
用法:将l 中的it->second迭代器插入l.begin()的位置,并从l中删除掉 it->second的迭代器元素
map.erase(key) : 删除 key 对应所在的元素
list.erase(iterator)
class LRUCache {
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
auto it = m.find(key);
if (it==m.end())return -1;
l.splice(l.begin(),l,it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = m.find(key);
// if (it!=m.end())
// {
// l.splice(l.begin(),l,it->second);
// }
// else
// {
// l.push_front(make_pair(key,value));
// m[key] = l.begin();
// if (l.size()>cap)
// {
// int k = l.rbegin()->first;
// l.pop_back();
// m.erase(k);
// }
// }
if (it!=m.end())l.erase(it->second);
l.push_front(make_pair(key,value));
m[key] = l.begin();
if (l.size()>cap)
{
int k = l.rbegin()->first;
l.pop_back();
m.erase(k);
}
}
unordered_map<int,list<pair<int,int> >::iterator >m;
list<pair<int,int>>l;
int cap;
};
/**
* 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);
*/