作为一个新的python程序员,我正在练习Leetcode中的LRU缓存问题 链接:https://leetcode.com/problems/lru-cache/
问题描述:
设计并实现了一种用于最近最少使用(LRU)缓存的数据结构。它应该支持以下操作:get和put。你知道吗
get(key)-如果缓存中存在该键,则获取该键的值(将始终为正数),否则返回-1。 put(键,值)-如果键不存在,则设置或插入值。当缓存达到其容量时,它应该在插入新项之前使最近最少使用的项无效。你知道吗
以下是Leetcode提供的解决方案:
from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self:
return - 1
self.move_to_end(key)
return self[key]
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self:
self.move_to_end(key)
self[key] = value
if len(self) > self.capacity:
self.popitem(last = False)
但是,我在提交代码时遇到以下错误:
第29行:AttributeError:'LRUCache'对象没有属性'\u OrderedDict\u root'
谁能给我一些提示我为什么会犯那个错误吗?真的很感激吗?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐