LRU緩存

6 阅读1分钟

題目

leetcode.cn/problems/lr…

題解

class LRUCache {
private:
    int cap;
    list<pair<int, int>> cache; // key-value
    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. 查 map2. splice 把該節點移到最前3. 返回值O(1)
put(key, value)插入或更新 key-value1. 查 map2. 如果存在 → 更新值 + splice3. 不存在 → 判斷容量4. 滿 → pop_back + map.erase5. 插入到前面 + map[key] = begin()O(1)