列表

详情


155. 最小栈

设计一个支持 pushpoptop 操作,并能在常数时间内检索到最小元素的栈。

实现 MinStack 类:

 

示例 1:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

 

提示:

相似题目

滑动窗口最大值

最大栈

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MinStack { public: MinStack() { } void push(int val) { } void pop() { } int top() { } int getMin() { } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */

python3 解法, 执行用时: 96 ms, 内存消耗: 18 MB, 提交时间: 2021-08-16 16:23:07

class MinStack:

    def __init__(self):
        self.stack = []
        self.min_stack = [math.inf] 

    def push(self, x: int) -> None:
        self.stack.append(x)
        self.min_stack.append(min(x, self.min_stack[-1])) #最小列表, 最后元素放最小的

    def pop(self) -> None:
        self.stack.pop()
        self.min_stack.pop() # 弹出栈顶最大元素

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.min_stack[-1]



# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

上一题