[LeetCode] - Min Stack O(1)最小栈

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)的时间里找出栈的最小值。


首先,想到的是,对于一个普通栈来说,不能实现O(1)找最小值。需要辅助,采用双栈:

Real stack        Min stack

5  --> TOP        1
4                 1
1                 1
3                 2
2                 2
辅助栈每次存入当前最小值,并同步压入和弹出即可。

但是以上问题是:Memory Limit Exceeded(消耗了2倍的空间)


优化: Min Stack 不必每次都存入,只需要存入最小值变化的状态。

Real stack        Min stack

5  --> TOP        1
4                 2
1                 
3                 
2                 
所以每次出栈的时要比较一下,

入栈时 curr< = Min Stack Top 则MinStack 也要入栈  

如果Real Stack top == Min Stack top  则 Min Stack 也需要pop()

注意:最小值可能会多次入栈的问题。

class MinStack{
public:
    void push(int x) {
         S.push(x);
         if(MinS.empty() || x<=MinS.top())
             MinS.push(x);
    }

    void pop(){
        int temp=S.top();
        S.pop();
        if(temp == MinS.top())
            MinS.pop();
    }

    int top(){
        return S.top();
    }
    int getMin(){
        return MinS.top();
    }
private:
    stack<int> S,MinS;
};





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值