class LRUCache {
public:
LRUCache(int capacity) {
this->capacity=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.erase(it->second);
else if(m.size()==capacity){
int k=l.back().first;
l.pop_back();
m.erase(k);
}
l.push_front(make_pair(key, value));
m[key]=l.begin();
}
private:
int capacity;
list<pair<int,int>>l;
unordered_map<int,list<pair<int,int>>::iterator>m;
};
146. LRU Cache
最新推荐文章于 2022-10-14 20:49:35 发布