NC93 设计LRU缓存结构解题思路

capacity = ["set", "set", "get", "set", "get", "set", "get", "get", "get"], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1],[3], [4]], 2

class Solution:

    def __init__(self, capacity: int):
        # write code here
        self.input_a, self.input_b, self.num = capacity
        self.lru_dict = {}
        self.lru_list = []
        self.return_list = []
        self.sun = []

    def get(self, key: int) -> int:
        # write code here
        if key not in self.lru_list:    # 如果key不存在key列表中则返回-1
            self.return_list.append(-1) 
            return 1
        self.lru_list.remove(key)   # 如果存在则删除该key值重新进入容器
        self.lru_list.append(key)
        self.return_list.append(self.lru_dict[key])


    def set(self, key: int, value: int) -> None:
        # write code here
        if len(self.lru_list) < self.num and key not in self.lru_list:  # 如果长度小于指定长度且,当前列表中不存在该key
            self.lru_list.append(key)
        else:                                   # 如果长度超出的话
            pop_key = self.lru_list.pop(0)  
            self.lru_dict.pop(pop_key)  # 故去掉某尾的key-value
            self.lru_list.append(key)   # 添加新的key
        self.lru_dict[key] = value  # 新添加键值对
        self.return_list.append('null')

    def run(self):
        for i in range(len(self.input_a)):
            if self.input_a[i] == 'set':
                solution.set(self.input_b[i][0], self.input_b[i][1])
            else:
                solution.get(self.input_b[i][0])
        print(self.return_list)


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

因为输入输出的问题以下代码是可以正常提交的(抄的正确答案)

class Solution:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.buf = dict()  

    def get(self, key: int) -> int:
        ret = self.buf.get(key, -1)
        if key in self.buf:
            self.buf.pop(key)
            self.buf[key] = ret
        return ret

    def set(self, key: int, value: int) -> None:
        if key in self.buf:
            self.buf.pop(key)
        elif len(self.buf) >= self.capacity:
            tmp = next(iter(self.buf.keys()))  # 快速获取第一个 key
            self.buf.pop(tmp)
        self.buf[key] = value
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值