【模拟-BM100 设计LRU缓存结构】

题目

BM100 设计LRU缓存结构

描述

设计LRU(最近最少使用)缓存结构,该结构在构造时确定大小,假设大小为 capacity ,操作次数是 n ,并有如下功能:

  1. Solution(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  2. get(key):如果关键字 key 存在于缓存中,则返回key对应的value值,否则返回 -1 。
  3. set(key, value):将记录(key, value)插入该结构,如果关键字 key 已经存在,则变更其数据值 value,如果不存在,则向缓存中插入该组 key-value ,如果key-value的数量超过capacity,弹出最久未使用的key-value

提示:

1.某个key的set或get操作一旦发生,则认为这个key的记录成了最常使用的,然后都会刷新缓存。

2.当缓存的大小超过capacity时,移除最不经常使用的记录。

3.返回的value都以字符串形式表达,如果是set,则会输出"null"来表示(不需要用户返回,系统会自动输出),方便观察

4.函数set和get必须以O(1)的方式运行

5.为了方便区分缓存里key与value,下面说明的缓存里key用""号包裹

分析

python 的话,直接用collection 中的 OrderedDict

OrderedDict 是 Python 标准库 collections 模块中的一个特殊字典类,其核心特性是维护了元素添加的顺序。这与 Python 3.7 及以上版本中的普通字典不同,尽管普通字典现在也保持插入顺序,但 OrderedDict 提供了一些额外的功能,这些功能在普通字典中不可用。

顺序性:

OrderedDict 记录了元素被添加到字典中的顺序。这对于需要元素顺序的场景(如实现LRU缓存)非常有用。

重排功能:

使用 move_to_end 方法可以将一个键值对移动到有序字典的末尾或开头,这在调整元素顺序时非常方便。

常用方法

popitem(last=True): 弹出并返回一个键值对。如果 last 为 True(默认值),则按 LIFO(后进先出)顺序返回最后一个添加的元素;如果为 False,则按 FIFO(先进先出)顺序返回第一个添加的元素。

move_to_end(key, last=True): 将存在的键 key 移动到字典的末尾(如果 last=True)或字典的开头(如果 last=False)。

示例代码

下面是一个简单的示例,展示了 OrderedDict 的一些基本用法:

python 复制代码
from collections import OrderedDict

# 创建有序字典
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3

# 访问顺序
for key, value in od.items():
    print(key, value)  # a 1, b 2, c 3

# 移动元素 'b' 到末尾
od.move_to_end('b')
for key, value in od.items():
    print(key, value)  # a 1, c 3, b 2

# 弹出最先加入的元素
od.popitem(last=False)
for key, value in od.items():
    print(key, value)  # c 3, b 2

代码

python 复制代码
from collections import OrderedDict


class Solution:

    def __init__(self, capacity: int):
    # write code here
        self.capacity = capacity
        self.lru_cache = OrderedDict()

    def get(self, key: int) -> int:
    # write code here
        if key in self.lru_cache:
            self.lru_cache.move_to_end(key)
        return self.lru_cache.get(key,-1)
    

    def set(self, key: int, value: int) -> None:
    # write code here
        if key in self.lru_cache:
            # self.lur_cache.move_to_end(key)
            del self.lru_cache[key]
        self.lru_cache[key] = value
        if len(self.lru_cache)>self.capacity:
            self.lru_cache.popitem(last=False)

# Your Solution object will be instantiated and called as such:
# solution = Solution(capacity)
# output = solution.get(key)
# solution.set(key,value)
相关推荐
z***565627 分钟前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
voidmort1 小时前
web3.py 简介:面向 Python 开发者的以太坊
开发语言·python·web3.py
后台开发者Ethan1 小时前
LangGraph 的持久化
python·langgraph
油炸小波1 小时前
02-AI应用开发平台Dify
人工智能·python·dify·coze
SunnyDays10112 小时前
从图片到PPT:用Python实现多图片格式(PNG/JPG/SVG)到幻灯片的批量转换
python·图片转ppt·png转ppt·jpg转ppt·svg转ppt·添加图片到ppt
妮妮喔妮3 小时前
pai 的redis存储
数据库·redis·缓存
CodeCraft Studio3 小时前
Excel处理控件Aspose.Cells教程:使用Python从Excel工作表中删除数据透视表
开发语言·python·excel·aspose·aspose.cells·数据透视表
普通网友3 小时前
用Python批量处理Excel和CSV文件
jvm·数据库·python
linuxxx1103 小时前
高考志愿填报辅助系统
redis·后端·python·mysql·ai·django·高考
无妄无望3 小时前
ragflow代码学习切片方式(1)docling_parser.py
人工智能·python·学习