題目
leetcode.cn/problems/lr…
題解
class LRUCache {
private:
int cap;
list<pair<int, int>> cache;
unordered_map<int, list<pair<int, int>>::iterator> mp;
public:
LRUCache(int capacity) : cap(capacity) {}
int get(int key) {
auto it = mp.find(key);
if (it == mp.end()) return -1;
cache.splice(cache.begin(), cache, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = mp.find(key);
if (it != mp.end()) {
cache.splice(cache.begin(), cache, it->second);
it->second->second = value;
} else {
if (cache.size() == cap) {
auto last = cache.back();
mp.erase(last.first);
cache.pop_back();
}
cache.emplace_front(key, value);
mp[key] = cache.begin();
}
}
};
操作 | 說明 | 操作細節 | 時間複雜度 |
---|
get(key) | 取出值並更新為最近使用 | 1. 查 map 2. splice 把該節點移到最前3. 返回值 | O(1) |
put(key, value) | 插入或更新 key-value | 1. 查 map 2. 如果存在 → 更新值 + splice 3. 不存在 → 判斷容量4. 滿 → pop_back + map.erase 5. 插入到前面 + map[key] = begin() | O(1) |