我正在尝试使用leetcode最小堆栈问题,但是我的代码无法正常工作,试图找到解决方案,但看不到问题所在。它似乎适用于大多数输入,但是失败“
[“ MinStack”,“ push”,“ push”,“ push”,“ top”,“ pop”,“ getMin”,“ pop”,“ getMin”,“ pop”,“ push”,“ top “,” getMin“,” push“,” top“,” getMin“,” pop“,” getMin“] [[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[ ],[],[],[]]”。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.count = 0
self.minEle = -1
def push(self, x: int) -> None:
if self.count == 0:
self.minEle = x
self.stack.append(x)
elif x < self.minEle:
self.stack.append(2*x - self.minEle)
self.minEle = x
elif x >= self.minEle:
self.stack.append(x)
self.count += 1
def pop(self) -> None:
y = self.stack.pop()
if y < self.minEle:
self.minEle = 2*self.minEle - y
self.count -= 1
def top(self) -> int:
if self.count >=1:
return self.stack[(self.count - 1)]
else:
return 0
def getMin(self) -> int:
return self.minEle
答案 0 :(得分:0)
尝试:
class MinStack:
def __init__(self):
self.sc = []
self.sm = []
# @param x, an integer
# @return an integer
def push(self, x):
self.sc.append(x)
if x <= self.getMin():
self.sm.append(x)
return x
# @return nothing
def pop(self):
if self.sc.pop() == self.getMin():
self.sm.pop()
# @return an integer
def top(self):
return self.sc[-1]
# @return an integer
def getMin(self):
try:
return self.sm[-1]
except IndexError:
return self.top()
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())
param_3 = obj.top()
param_4 = obj.getMin()