代码拉取完成,页面将自动刷新
同步操作将从 陌溪/LearningNotes 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
class LRUCache(object):
def __init__(self, capacity):
self.capacity = capacity
self.map = {}
self.array = []
self.size = 0
def get(self, key):
if self.map.get(key):
index = self.array.index(key)
# 将该元素移动到最新使用的
del self.array[index]
self.array.append(key)
return self.map.get(key)
else:
return -1
def put(self, key, value):
if self.size < self.capacity:
if self.map.get(key):
# 将该元素移动到最新使用的
index = self.array.index(key)
del self.array[index]
self.array.append(key)
# 更新key
self.map[key] = value
else:
self.map[key] = value
self.array.append(key)
self.size += 1
else:
if self.map.get(key):
# 将该元素移动到最新使用的
index = self.array.index(key)
del self.array[index]
self.array.append(key)
# 更新key
self.map[key] = value
else:
# 淘汰第一个,在最后插入元素
deleteKey = self.array.pop(0)
del self.map[deleteKey]
self.map[key] = value
self.array.append(key)
if __name__ == '__main__':
cache = LRUCache(2)
print(cache.get(2))
cache.put(2, 6)
print(cache.get(1))
cache.put(1, 5)
cache.put(1, 2)
print(cache.get(1))
print(cache.get(2))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。