题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
用有序容器保存hashmap中key的顺序
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 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
templ = []
tempd = dict()
answer = []
for i in operators:
if i[0] == 1:
if i[1] in tempd:
templ.remove(i[1])
templ.insert(0, i[1])
tempd[i[1]] = i[2]
else:
if len(templ) < k:
tempd[i[1]] = i[2]
templ.insert(0, i[1])
else:
x = templ.pop()
templ.insert(0, i[1])
tempd.pop(x)
tempd[i[1]] = i[2]
elif i[0] == 2:
if i[1] in tempd:
templ.remove(i[1])
templ.insert(0, i[1])
answer.append(tempd[i[1]])
else:
answer.append(-1)
return answer