题目:146. LRU Cache
题意: 实现LRU (最近最少使用) 缓存机制,get方法和set方法
思路:hash用来查找key,list用来存储结点
get:key存在返回,否则返回-1
set:key存在,直接将此结点在list置前;不存在插入list首部,超过容量pop_back
.splice() 用来将list 2中的某个结点插入list 1特定位置
代码:
class LRUCache {
public:
int cap;
list<pair<int,int>> cache;
unordered_map<int, list<pair<int,int>>::iterator> hash;
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
auto it = hash.find(key);
if(it == hash.end())
return -1;
cache.splice(cache.begin(), cache, it->second);//最近使用,置前
return it->second->second;
}
void put(int key, int value) {
auto it = hash.find(key);
if(it != hash.end()){//存在
it->second->second = value;
cache.splice(cache.begin(), cache, it->second);//最近使用,置前
}
else{
cache.insert(cache.begin(), make_pair(key, value));
hash[key] = cache.begin();
if(cache.size() > cap){
hash.erase(cache.back().first);//在map中删掉
cache.pop_back();//在list中删掉
}
}
}
};
/**
* 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);
*/