//高效的get决定了需要有hash
//每次操作都要将被操作的数的最近访问信息进行调整,涉及随机位置的变换,即从中间移动到队首,需要list在o(1)中移动节点
class LRUCache {
public:
list<pair<int, int>> l_;
unordered_map<int, list<pair<int, int>>::iterator> m_;
int capacity_;
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
auto k = m_.find(key);
if(k == m_.end()) return -1;
l_.splice(l_.begin(), l_, k->second);//物理地址并没有变,所以key对应的list中的地址并没有变,只是在逻辑上成了头了
return k->second->second;
}
void put(int key, int value) {
auto p = m_.find(key);
if(p != m_.end()){
p->second->second = value;
l_.splice(l_.begin(), l_, p->second);
}else{
if(l_.size() >= capacity_){
int key_remove = l_.back().first;
l_.pop_back();
m_.erase(key_remove);
}
l_.insert(l_.begin(), make_pair(key, value));
m_.insert(make_pair(key, l_.begin()));
}
return;
}
};
/**
* 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);
*/
【Leetcode146】 LRU Cache
猜你喜欢
转载自blog.csdn.net/weixin_39458342/article/details/105009072
今日推荐
周排行