Разработка максимального стека, который поддерживает pu sh, pop, top, peekMax и popMax.
push(x) -- Push element x onto stack.
pop() -- Remove the element on top of the stack and return it.
top() -- Get the element on the top.
peekMax() -- Retrieve the maximum element in the stack.
popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.
*
Example 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
*
Примечание: -1e7 <= x <= 1e7 Количество операций не будет превышать 10000. Последние четыре операции не будут вызываться, когда стек пуст. </p>
Код, который я написал:
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
if not self.stack:
self.stack.append((x,x))
return
self.stack.append((x,max(x,self.stack[-1][1])))
def pop(self) -> int:
return self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def peekMax(self) -> int:
return self.stack[-1][1]
def popMax(self) -> int:
b = self.stack[-1][1]
m = []
while b!=self.stack[-1][0]:
m.append(self.pop())
self.pop()
map(self.push, reversed(m))
return b
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()
**
Input: ["MaxStack","push","push","push","top","popMax","top","peekMax","pop","top"]
[[],[5],[1],[5],[],[],[],[],[],[]]
My Output: [null,null,null,null,5,5,1,5,(1, 5),5]
Expected Output: [null,null,null,null,5,5,1,5,1,5]
**
Мне кажется, проблема в функции popMax (). У меня есть несколько сомнений здесь. 1. В функции popMax (), когда я вызываю уже определенные функции, я вызываю self.stack.pop() or self.pop()
? 2. Также скажите пожалуйста, где я ошибся в последней функции