我试图通过以下解决方案在Visual Studio Code上解决此Leetcode问题:
class CustomStack:
vals = list()
def __init__(self, maxSize):
self.maxSize = maxSize
def push(self, x):
if len(self.vals) < self.maxSize:
self.vals.append(x)
print(self.vals)
def pop(self):
if len(self.vals) > 0:
val = self.vals.pop()
print(val)
return val
else:
print(-1)
return -1
def increment(self, k, val):
k = min(k, len(self.vals))
for i in range(k):
self.vals[i] += val
print(self.vals)
它在VSCode上打印正确的数字:[null,null,34,null,-1,null,null,63,null,null,null,null]
但是它在打印[null,null,85,null,181,null,null,196,null,null,null,null的LeetCode上失败]
我知道正确的解决方案可能是这样:
class CustomStack:
def __init__(self, maxSize):
self.vals =[]
self.maxSize = maxSize
但是为什么原始版本适用于VSCode,而不适用Leetcode?
CustomStack
类的一个实例来测试一个示例。在LeetCode中,使用CustomStack
类的新实例执行多个测试用例。由于vars
是类变量,而不是实例变量,因此它将在程序执行期间创建的所有CustomStack
实例之间共享。这意味着每个实例都修改相同的list
。您已经展示了实现特定于类实例的变量的正确方法是在__init__
方法中对其进行定义:
class CustomStack:
def __init__(self, maxSize):
self.vals =[]
self.maxSize = maxSize