[力扣 Hot100]Day35 LRU 缓存

题目描述

请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。

实现 LRUCache 类:

LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存

int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。

void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。

函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

出处

思路

写了两个版本都超时,单向链表和迭代器的查找都太慢,需要用哈希表。

代码

cpp 复制代码
class LRUCache {
private:
    int len;
    list<pair<int, int>> lru;
    unordered_map<int, list<pair<int, int>>::iterator> map;
public:
    LRUCache(int capacity) {
        len=capacity;
    }
    
    int get(int key) {
        if (map.find(key) == map.end()) return -1;
        pair<int,int> key_value = *map[key];
        lru.erase(map[key]);
        lru.push_front(key_value);
        map[key] = lru.begin();
        return key_value.second;
    }
    
    void put(int key, int value) {
        if (map.find(key) == map.end()) {
            if (lru.size() == len) {
                map.erase(lru.back().first);
                lru.pop_back();
            }
        }
        else {
            lru.erase(map[key]);
        }
        lru.push_front({key, value});
        map[key] = lru.begin();
    }
};
相关推荐
yong99901 天前
LSD直线提取算法 MATLAB
开发语言·算法·matlab
MobotStone1 天前
一文看懂AI智能体架构:工程师依赖的8种LLM,到底怎么分工?
后端·算法·llm
lengxuenong1 天前
潍坊一中第四届编程挑战赛(初赛)题解
算法
松涛和鸣1 天前
25、数据结构:树与二叉树的概念、特性及递归实现
linux·开发语言·网络·数据结构·算法
Han.miracle1 天前
数据结构--初始数据结构
算法·集合·大o表示法
List<String> error_P1 天前
C语言联合体:内存共享的妙用
算法·联合体
little~钰1 天前
可持久化线段树和标记永久化
算法
獭.獭.1 天前
C++ -- 二叉搜索树
数据结构·c++·算法·二叉搜索树
TOYOAUTOMATON1 天前
自动化工业夹爪
大数据·人工智能·算法·目标检测·机器人
im_AMBER1 天前
Leetcode 67 长度为 K 子数组中的最大和 | 可获得的最大点数
数据结构·笔记·学习·算法·leetcode