[leetcode 155] Min Stack

19 篇文章 0 订阅

Question:

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

分析:

方法1:

利用两个栈,栈1作为MinStack,栈2按序存放最小值,比如输入为5、4、2、1、1、7则栈2为5、4、2、1、1.在出栈的时候注意,如果出栈的值等于最小值,则将栈2中的栈顶删除;

代码如下:

<span style="font-size:14px;">class MinStack {
private:
    stack<int> s1;
    stack<int> s2;
public:
    void push(int x) {
        s1.push(x);
        if (s2.empty() || x <= getMin())  s2.push(x);       
    }
    void pop() {
        if (s1.top() == getMin())  s2.pop();
        s1.pop();
    }
    int top() {
        return s1.top();
    }
    int getMin() {
        return s2.top();
    }
};</span>


方法2:

利用pair<int,int>,第一个值记录如栈值,第二个记录到此为止的最小值。

代码如下:


<span style="font-size:14px;">public:
    void push(int x) {
        int min;
        if (st.empty()) {
            min = x;
        }
        else {
            min = st.top().second<x? st.top().second:x;
        }
        pair<int, int>p(x, min);
        st.push(p);
    }

    void pop() {
        st.pop();
    }

    int top() {
        return st.top().first;
    }

    int getMin() {
        return st.top().second;
    }</span>



方法3:

理论同上,方法实现不同。

代码如下

<span style="font-size:14px;">public:
    vector<int> stack;
    vector<int> min;
    MinStack(){
        min.push_back(INT_MAX);
    }
    
public:
    void push(int x) {
        stack.push_back(x);
        if(x < min.back())
            min.push_back(x);
        else
            min.push_back(min.back());
    }

    void pop() {
        stack.pop_back();
        min.pop_back();
    }

    int top() {
        return stack.back();
    }

    int getMin() {
        return min.back();
    }</span>



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值