LRU算法 C++

源码

#pragma once

#include <list>
#include <unordered_map>
using namespace std;
class LRUCache
{
public:
    LRUCache(int capacity) : cap(capacity)
    {
        m.reserve(capacity);
        m.max_load_factor(0.75);
    }

    int get(int key)
    {
        auto it = m.find(key);
        if (it == m.cend())
            return -1;
        l.splice(l.begin(), l, it->second);
        return it->second->second;
    }

    void put(int key, int value)
    {
        auto it = m.find(key);
        if (it != m.cend())
        {
            l.erase(it->second);
        }
        else if (m.size() >= cap)
        {
            int k = l.rbegin()->first;
            l.pop_back();
            m.erase(k);
        }
        l.emplace_front(make_pair(key, value));
        m[key] = l.begin();
    }

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

测试代码


#include "lru.hpp"
#include <iostream>
using namespace std;


int main() {
    LRUCache cache(2);
    cache.put(1, 1);
    cache.put(2, 2);
    cout << cache.get(1);       // 返回1

    cache.put(3, 3);            
    cout << cache.get(2);       // 返回-1

    cache.put(4, 4);             
    cout << cache.get(1);       // 返回-1
    cout << cache.get(3);       // 返回3
    cout << cache.get(4);       // 返回4
    
    cache.put(4,5);
    cout << cache.get(4);       // 返回5

    
    return 0;
}

posted @   天下太平  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示