0155.最小栈

https://leetcode-cn.com/problems/min-stack

原题

设计一个支持 push , pop , top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素。

示例:

  1. 输入:
  2. ["MinStack","push","push","push","getMin","pop","top","getMin"]
  3. [[],[-2],[0],[-3],[],[],[],[]]
  4. 输出:
  5. [null,null,null,null,-3,null,0,-2]
  6. 解释:
  7. MinStack minStack = new MinStack();
  8. minStack.push(-2);
  9. minStack.push(0);
  10. minStack.push(-3);
  11. minStack.getMin(); --> 返回 -3.
  12. minStack.pop();
  13. minStack.top(); --> 返回 0.
  14. minStack.getMin(); --> 返回 -2.

提示:

  • pop 、 top 和 getMin 操作总是在 非空栈 上调用。

标签
栈 设计

思路

两个栈,一个正常,一个从大到小,分别为 A,B
push x:
A push x
B 如果 x 小于等于栈顶,或者栈空,加入
pop:
A pop
B 如果栈顶等于 A 的栈顶 pop

top: A.top
min: B.top

代码

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> A, B;
    MinStack() {

    }

    void push(int x) {
        A.push(x);

        if(B.empty() || x <= B.top()) B.push(x);
    }

    void pop() {
        int t = A.top();
        A.pop();

        if(B.top() == t) B.pop();
    }

    int top() {
        return A.top();
    }

    int min() {
        return B.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->min();
 */

参考:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/solution/mian-shi-ti-30-bao-han-minhan-shu-de-zhan-fu-zhu-z/