[力扣 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();
    }
};
相关推荐
Tony_yitao1 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹2 小时前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅2 小时前
代码随想录 463.岛屿的周长
算法
一个不知名程序员www2 小时前
算法学习入门---priority_queue(C++)
c++·算法
TL滕3 小时前
从0开始学算法——第十八天(分治算法)
笔记·学习·算法
LYFlied3 小时前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展
CoderCodingNo3 小时前
【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作
开发语言·c++·算法
Liangwei Lin4 小时前
洛谷 P1955 [NOI2015] 程序自动分析
算法
zwjapple4 小时前
全栈开发面试高频算法题
算法·面试·职场和发展