我正在研究LeetCode问题LRU Cache,并且想了解为什么我的代码不起作用。
我的想法是保留有效键的队列和元组(isValid, value)
的字典。每次调用get
时,我想使队列中的下一个键无效,并将该键的字典元组更新为(False, value)
。
我知道那里有更好的解决方案,我真的很想知道为什么我的不起作用,因此我通常可以成为一个更好的调试器/程序员。提前非常感谢您提供的所有帮助!
到目前为止,这是我的代码:
class LRUCache:
def __init__(self, capacity: int):
self.d = dict()
self.capacity = capacity
self.validKeys = Queue()
def get(self, key: int) -> int:
(isValid, value) = self.d.get(key, (False, -1))
if isValid:
return value
else:
return -1
def put(self, key: int, value: int) -> None:
if self.validKeys.getSize() >= self.capacity:
lastUsedKey = self.validKeys.dequeue()
(_, val) = self.d[lastUsedKey]
self.d[lastUsedKey] = (False, val)
# only enqueue a new key if it doesn't exist in the cache already, was part of the problem statement
if self.d.get(key, None) is None:
self.d[key] = (True, value)
self.validKeys.enqueue(key)
这是预期的输出:
[null,null,null,1,null,-1,null,-1,3,4]
这是我的输出:
[null,null,null,1,null,2,null,-1,3,4]
注意:我很确定我的队列实现是正确的,我已经在下面用我测试过的测试用例发布了它:
class Node:
def __init__(self, val):
self.prev = None
self.next = None
self.val = val
class Queue:
def __init__(self):
self.head = None
self.tail = self.head
self.size = 0
def enqueue(self, val):
if self.size == 0:
self.head = Node(val)
self.tail = self.head
else:
self.tail.next = Node(val)
self.tail = self.tail.next
self.size += 1
def dequeue(self):
if self.size == 0:
raise "Queue empty"
else:
val = self.head.val
self.head = self.head.next
self.size -= 1
return val
def getSize(self):
return self.size
def __repr__(self):
curr = self.head
res = ''
while curr is not None:
res += str(curr.val)
curr = curr.next
return res
obj = Queue()
assert obj.getSize() == 0
obj.enqueue(1)
assert obj.getSize() == 1
assert obj.dequeue() == 1
assert obj.getSize() == 0
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
assert obj.getSize() == 3
assert obj.dequeue() == 1
assert obj.dequeue() == 2
assert obj.dequeue() == 3
assert obj.getSize() == 0