剑指offer Leetcode 30. 包含min函数的栈

image-20201207193542499

解法1:辅助栈

思想:

​ push和pop操作本来就是O(1),所以只需要一个辅助栈来实现O(1)的min就好了。

​ 辅助栈B的栈顶就是A中元素的最小值

image-20201207194217615
代码:
class MinStack {
private:
    stack<int>A;
    stack<int>B;
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        A.push(x);
        // 这里不要跟单调队列的做法搞混
        //在B为空或者新的值小于等于B的top时,将x放入B
        if(B.empty() || x <= B.top())
            B.push(x);
    }
    //如果要pop的值和B的top相等,B也pop
    void pop() {
        if(A.top() == B.top())
            B.pop();
        A.pop();
    }
    
    int top() {
        return A.top();
    }
    
    int min() {
        return B.top();
    }
};

解法2:一个栈,两个数据位合成一个单元

思想:

​ 用两个数据位作为一个单元,第一个存储数据本身,第二个存储当前的最小值

代码:
class MinStack {
private:
    stack<int>s;
public:
    /** initialize your data structure here. */
    MinStack() {

    }
    
    void push(int x) {
  		//为空的时候直接push两次
        if(s.empty()){
            s.push(x);
            s.push(x);
        }
        //不为空,最小值要比较后再push
        else{
            int tmp = s.top();
            s.push(x);
            s.push(x < tmp ? x : tmp);
        }
    }
    
    void pop() {
        s.pop();
        s.pop();
    }
    
    //top是最小值,所以要pop并保存,再取top
    int top() {
        int tmp = s.top();
        s.pop();
        int ret = s.top();
        s.push(tmp);
        return ret;
    }
    
    int min() {
        return s.top();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值