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