[LeetCode]155. Min Stack

辅助栈的应用

Posted by JinFei on December 23, 2019

题目描述

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.

解题思路

  • 如果辅助栈为空,则还需要将元素插入到辅助栈
  • 如果不为空,比较插入的元素和辅助栈的top大小,如果小于等于辅助栈的top大小,则还需要插入辅助栈
  • 弹出的时候,如果s1弹出的元素等于s2栈的头元素,则还需要将s2弹出
class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty()){
            s2.push(x);
        }else if(x <= s2.top()){
            s2.push(x);
        }
    }
    
    void pop() {
        int x = s1.top();
        s1.pop();
        if(x == s2.top()){
            s2.pop();
        }
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
private:
    stack<int> s1;
    stack<int> s2;
};

/**
 * 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->getMin();
 */