原题链接:https://leetcode-cn.com/problems/lru-cache/
题目要求O(1),于是采用哈希表方法,又由于要满足LRU机制,故采用链表保存
class LRUCache {
public:
int capacity;
list<int> keyList;
unordered_map<int, pair<int, list<int>::iterator>> mp;
LRUCache(int n) {
capacity = n;
}
void insert(int key, int value) {
keyList.push_back(key);
mp[key] = {value, --keyList.end()};
}
int get(int key) {
if (mp.count(key)) {//如果存在,则删除并添加,否则返回-1
int value = mp[key].first;
keyList.erase(mp[key].second);
insert(key, value);
return value;
}
return -1;
}
void put(int key, int value) {
if (mp.count(key)) {//如果存在,则删除
keyList.erase(mp[key].second);
mp.erase(mp.find(key));
} else {
if (mp.size() == capacity) {//如果满了,则删除最近没使用的
int k = keyList.front();
mp.erase(mp.find(k));
keyList.pop_front();
}
}
insert(key, value); //添加元素
}
};