155. 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.
Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

思路:

一开始肯定想到用一个currentMin来记住最小。这种方法不行是因为不支持连续的getMin()操作,因为不知道再之前最小的值。所以方法1就是用一个同等大小的栈来记录当前所有存储元素的最小值就行了。

方法1: 双栈

https://www.youtube.com/watch?v=5h42eila268
在这里插入图片描述

易错点:

  1. pop时候两栈都要pop
class MinStack {
public:
    /** initialize your data structure here. */
    
    MinStack() {
        
    }
    
    void push(int x) {
        if (helper.empty() || x < helper.top() ) helper.push(x);
        else helper.push(helper.top());
        st.push(x);
    }
    
    void pop() {
        st.pop();
        helper.pop();
    }
    
    int top() {
        return st.top();
    }
    
    int getMin() {
        return helper.top();
    }
private:
    stack<int> st, helper;
    
};

改进: 在这里插入图片描述
如果x > top(), 不用向helperStack里面推。这个方法对于increasing order只需要推一次,但如果是个decreasing序列空间复杂度并不改变。

方法2: 单栈

思路:

这个方法是在每次更替最小值时候,将previous_min先推进去。举例子:

[“MinStack”,“push”,“push”,“push”,“push”, “push”, “push”, “getMin”,“pop”,“top”,“getMin”]
[[],[-2],[0],[-3],[-5], [-3], [-1],[],[],[],[]]

stack [-2, 0, -2, -3, -3, -5, -3, -1 ]
push [ _, _, __, (^ *), (^ * ), _`]
min_val[ -2, -2, -2, -3, -5, -5, -5]

当pop出元素时,如果栈顶元素不等于min_val时,直接pop掉。如果栈顶元素等于当前min_val, 再之前一个元素是previous_min, 取回代替min_val 之后再pop掉一次。多存的一个元素只用来retrieve之前左右元素的最小值,只在pop时候使用一次就扔掉了。

易错点:

  1. 当x <= min_val, 更替,多push一次
  2. 当pop出的元素 = min_val,多pop一次
class MinStack {
public:
    /** initialize your data structure here. */
    
    MinStack() {
        min_val = INT_MAX;
    }
    
    void push(int x) {
        if (x <= min_val) {
            st.push(min_val);
            min_val = x;
        }
         st.push(x);
    }
    
    void pop() {
        int val = st.top();
        st.pop();
        if (val == min_val) {
            min_val = st.top();
            st.pop();
        }
    }
    
    int top() {
        return st.top();
    }
    
    int getMin() {
        return min_val;
    }
private:
    stack<int> st;
    int min_val;
};

方法3: 三栈,四栈

https://www.youtube.com/watch?v=5h42eila268

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值