1、关键点:map 和 list 要进行同步的更新,不能遗漏对map的操作
2、list容器的splice函数合并两个list合理使用可以加快 list 中节点顺序的调整
list::splice()函数: https://blog.csdn.net/qjh5606/article/details/85881680
3、push_front() 与 emplace_front() 的区别:
https://blog.csdn.net/fengbingchun/article/details/78670376
http://blog.guorongfei.com/2016/03/16/cppx-stdlib-empalce/
class LRUCache {
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
auto it = m.find(key);
if(it == m.end()) return -1;
auto lit = it->second;
l.splice(l.begin(), l, lit); //将l中的lit迭代器指向的节点删除,并插入到l.begin()之前
return lit->second;
}
void put(int key, int value) {
auto it = m.find(key);
//if(it != m.end()) return; //如果已经存在key,也不能return,需要更新key的值
if(it != m.end()) {
it->second->second = value;
l.splice(l.begin(), l, it->second);
return;
}
//如果key不存在
if(l.size()==capacity_) {
auto& node = l.back(); //返回最后一个元素, 赋值给一个引用变量
m.erase(node.first); //根据节点的key值删除map中对应的key-value对
l.pop_back(); //list l的最后一个元素删除,在此之前要把map中的key也删除!!!
}
//l.push_front(pair<key, value>);
//l.push_front(key, value); //no matching function for call to 'std::__cxx11::list<std::pair<int, int> >::push_front(int&, int&)'
l.push_front({key, value});
//l.emplace_front(key, value); //C++11中新增的函数,避免了产生不必要的中间变量,加快速度
m[key] = l.begin();
}
private:
/*struct Node{
unsigned int value;
Node* next;
};
list<Node> l;*/
//利用STL中的list容器实现链表,节点元素不需要再定义next指针,因此上面的代码多余
int capacity_; //容量
list<pair<int, int>> l; //一组key,value存入list
unordered_map<int, list<pair<int, int>>::iterator> m;
};
/**
* 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);
*/