【模拟-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)
相关推荐
笨鸟先飞,勤能补拙2 小时前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
长和信泰光伏储能3 小时前
京津冀光伏发电:绿色能源的未来之路
python·能源
浦信仿真大讲堂3 小时前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
Gu Gu Study4 小时前
ScoutLoop开放域深度研究引擎(agent的初步设计想法)
人工智能·python
卷无止境4 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境4 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
lpfasd1234 小时前
MediaCrawler 项目深度分析
chrome·python·chrome devtools
Dxy12393102165 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
bamb005 小时前
一个项目带你入门AI应用开发01
python
0566466 小时前
Python康复训练——常用标准库
开发语言·python·学习