题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# lru design
# @param operators int整型二维数组 the ops
# @param k int整型 the k
# @return int整型一维数组
#
class Solution:
def LRU(self , operators: List[List[int]], k: int) -> List[int]:
# write code here
stack = []
res = []
lru = {}
for op in operators:
if(op[0] == 1):
if(len(stack) >= k):
del lru[stack.pop(0)]
if(op[1] in lru):
stack.pop(stack.index(op[1]))
stack.append(op[1])
lru[op[1]] = op[2]
elif(op[0] == 2):
if(op[1] not in lru):
res.append(-1)
else:
res.append(lru[op[1]])
stack.append(stack.pop(stack.index(op[1])))
return res