题解 | #设计LRU缓存结构#

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

# Your Solution object will be instantiated and called as such:
# solution = Solution(capacity)
# output = solution.get(key)
# solution.set(key,value)
from collections import OrderedDict


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

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        else:
            # if the item exist, mark it as the most recently used
            self.cache.move_to_end(key)
            return self.cache[key]

    def set(self, key: int, value: int) -> None:
        self.cache[key] = value
        self.cache.move_to_end(key)
        # if the cache size exceed the capacity, remove the least used item
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 16:13
点赞 评论 收藏
分享
Twilight_m...:还是不够贴近现实,中关村那块60平房子200万怎么可能拿的下来,交个首付还差不多
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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