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:
# 这一步很容易忽略,不论 key 是否存在,都应该先 pop,这样重新加入时才可以更新到队尾
if key in self.buf:
self.buf.pop(key)
elif len(self.buf) >= self.capacity: # key not in self.buf
tmp = next(iter(self.buf.keys()))
self.buf.pop(tmp)
self.buf[key] = value