155. Min Stack

1、题目描述

设计stack,能返回其中的最小值。


2、思路

用一个数字m记录最小值,每次push都更新最小值,

当pop时,如果栈顶是最小值,则需要更新m;

否则直接弹出栈顶元素。


法2:用另一个stack保存最小值。

pop的时候,如果弹出的是最小值,另一个stack也要跟着弹出。


3、代码

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int>s;
    int m;
    MinStack() {
        m=INT_MAX;
    }
    
    void push(int x) {
        s.push(x);
        m=min(x,m);
    }
    
    void pop() {
        
        if(s.top()==m){
            s.pop();
            stack<int>s1;
            m=INT_MAX;
            while(!s.empty()){
                int t=s.top();
                s.pop();
                m=min(t,m);
                s1.push(t);
            }
            while(!s1.empty()){
                int t=s1.top();
                s1.pop();
                s.push(t);
            }
        
        
        }
        else s.pop();
            
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return m;
    }
};
class MinStack {
public:
    /** initialize your data structure here. */
    stack<int>s,s2;
    MinStack() {
    }
    
    void push(int x) {
        s.push(x);
        if(s2.empty() || s2.top() >= x)
            s2.push(x);
    }
    
    void pop() {
        int x = s.top();
        s.pop();
        if(x == s2.top())
            s2.pop();
            
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return s2.top();
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值