LRU Cache 最近最少使用
146. LRU 缓存 - 力扣(LeetCode)
链表:增删改O(1)
哈希表:增删改查O(1)
模板:
class LRUCache
{
public:LRUCache(int capacity) :_capacity(capacity){}int get(int key) {auto iter = _hashmap.find(key);if(iter != _hashmap.end()){auto listIter = iter->second;pair<int,int> tmp = *listIter;_list.erase(listIter);_list.push_front(tmp);_hashmap[key] = _list.begin();return tmp.second;}return -1;}void put(int key, int value) {auto iter = _hashmap.find(key);//不存在if(iter == _hashmap.end()){//LRU淘汰if(_capacity <= _list.size()){_hashmap.erase(_list.back().first);_list.pop_back();}_list.push_front(make_pair(key,value));_hashmap[key] = _list.begin();}else{auto listIter = iter->second;pair<int,int> tmp = *listIter;tmp.second = value;_list.erase(listIter);_list.push_front(tmp);_hashmap[key] = _list.begin();}}
private:size_t _capacity;list<pair<int,int>> _list; //使用list--增删改O(1)unordered_map<int, list<pair<int,int>>::iterator> _hashmap; //使用unordered_map--增删查改O(1)
};