题解 | 设计LRU缓存结构

from collections import OrderedDict


class Solution:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache:
            return -1
        value = self.cache.pop(key)
        self.cache[key] = value
        return value

    def set(self, key, value):
        if key in self.cache:
            self.cache.pop(key)
        elif len(self.cache) >= self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = value
        return None


全部评论
leetcode不就有吗
点赞 回复 分享
发布于 2025-04-30 11:16 北京
使用有序字典(OrderedDict)之后代码量明显下降。 有序字典是collections 里自带的,而collections 是Pyhton标准库,或者说:也是自带的。所有可以用
点赞 回复 分享
发布于 2025-02-25 13:57 河北

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务