LeetCode|Min Stack

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

思路:
O(1)的方法:用两个stack来模拟。

  • s1正常压栈、出栈。
  • s2用来记录最小值,栈顶表示当前的最小值。如果压栈的x 大于等于 s2的栈顶,压x入栈s2。如果s1出栈时的栈顶等于s2的栈顶,s2执行pop。

至于复杂度为什么是O(1),因为每次压栈、出栈操作都不带循环、递归。
另:这是我大二数据结构课的期末机试题之一,当时就没想到这种方法。当时是用multiset来当做s2的,每次push和pop都是O(logn)的,所以超时了。

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    void push(int x) {
        s1.push(x);
        if(s2.empty()){
            s2.push(x);
        } else if(s2.top() >= x){
            s2.push(x);
        }
    }
    void pop() {
        if(!s1.empty()){
            if(s1.top() == s2.top()){
                s2.pop();
            }
            s1.pop();
        }
    }
    int top() {
        if(!s1.empty())
            return s1.top();
        return -1;
    }
    int getMin() {
        if(!s2.empty()){
            return s2.top();
        } return -1;
    }
private:
stack<int> s1, s2;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值