欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 155. Min Stack

程序员文章站 2024-01-19 16:49:58
...

155. Min Stack

LeetCode 155. Min Stack

解析

这题不会写,(弱鸡(;´д`)ゞ)。看了discuss。C++using two stacks quite short and easy to understand

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {

    }

    void push(int x) {
        if(s2.empty() || x <=getMin())
            s2.push(x);
        s1.push(x);
    }

    void pop(){
        if(s1.top() == getMin())
            s2.pop();
        s1.pop();
    }

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

    int getMin() {
        return s2.top();
    }
private:
    stack<int> s1;
    stack<int> s2;
};