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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了