LRU

参考:
https://blog.csdn.net/bell10027/article/details/80940260

class LRUCache:

    def __init__(self, capacity: int):
        self.dic = collections.OrderedDict()
        self.remain = capacity

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

    def put(self, key: int, value: int) -> None:
        if key in self.dic:
            self.dic.pop(key)
        else:
            if self.remain > 0: # 记录LRU现在有多少个空位,如果还有空位,则直接put,否则先pop,再put
                self.remain -= 1
            else:
                self.dic.popitem(last=False) 
                # The pairs are returned in LIFO order if last is true or FIFO order if false.
        self.dic[key] = value

LRU

相关文章:

  • 2021-10-02
  • 2021-09-03
猜你喜欢
  • 2022-01-25
  • 2021-06-19
  • 2021-12-02
相关资源
相似解决方案