LRU
LRU缓存机制leetcode题
class LRUCache {
typedef list<pair<int,int>> LRUlist;
typedef list<pair<int,int>>::iterator LRU_LIST_IT;
public:
LRUCache(int capacity){
_capacity=capacity;
}
int get(int key) {
auto it=_kMapIt.find(key);
if(it==_kMapIt.end())
{
return -1 ;
}
else
{
LRU_LIST_IT itit=it->second;
int value=itit->second;
_LRUlist.splice(_LRUlist.end(),_LRUlist,itit);
return value;
}
}
void put(int key, int value) {
auto it=_kMapIt.find(key);
if(it==_kMapIt.end())
{
if(_LRUlist.size()>=_capacity)
{
_kMapIt.erase(_LRUlist.front().first);
_LRUlist.pop_front();
}
_LRUlist.push_back(make_pair(key,value));
_kMapIt[key]=--_LRUlist.end();
}
else
{
LRU_LIST_IT itit=it->second;
itit->second=value;
_LRUlist.splice(_LRUlist.end(),_LRUlist,itit);
}
}
private:
LRUlist _LRUlist;
unordered_map<int,LRU_LIST_IT> _kMapIt;
size_t _capacity;
};