This action will force synchronization from 陌溪/LearningNotes, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
class LRUCache(object):def __init__(self, capacity):self.capacity = capacityself.map = {}self.array = []self.size = 0def 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 -1def 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)# 更新keyself.map[key] = valueelse:self.map[key] = valueself.array.append(key)self.size += 1else:if self.map.get(key):# 将该元素移动到最新使用的index = self.array.index(key)del self.array[index]self.array.append(key)# 更新keyself.map[key] = valueelse:# 淘汰第一个,在最后插入元素deleteKey = self.array.pop(0)del self.map[deleteKey]self.map[key] = valueself.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))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。