solution.cpp 949 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class LRUCache
{
public:
    LRUCache(int capacity) : cap(capacity) {}

    int get(int key)
    {
        if (m.count(key) != 0)
        {
            int val = m[key]->second;
            l.erase(m[key]);
            l.push_front({key, val}); //访问过的元素移动到头部
            m[key] = l.begin();
            return val;
        }
        return -1;
    }

    void put(int key, int value)
    {
        if (m.count(key) != 0)
        { //已经存在
            l.erase(m[key]);
            l.push_front({key, value});
            m[key] = l.begin();
        }
        else
        {
            if (l.size() == cap)
            { //同步删除
                m.erase(l.back().first);
                l.pop_back();
            }
            l.push_front({key, value});
            m[key] = l.begin();
        }
    }

private:
    int cap;
    list<pair<int, int>> l;
    unordered_map<int, list<pair<int, int>>::iterator> m;
};