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

设计LRU缓存结构

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

from collections import OrderedDict
class Solution:

    def __init__(self, capacity: int):
        # write code here
        self.size = 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:
            del self.lru_cache[key]
        self.lru_cache[key] = value
        if len(self.lru_cache) > self.size:
            self.lru_cache.popitem(last=False)
全部评论

相关推荐

评论
8
收藏
分享

创作者周榜

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