c_cpp 155. Min Stack

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 155. Min Stack相关的知识,希望对你有一定的参考价值。

//Runtime: 40 ms, faster than 11.69%

class MinStack {
private:
    stack<int> s1;
    stack<int> s2;
    
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    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();
    }
};

/**
 * 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();
 */
//Runtime: 28 ms, faster than 53.45%

class MinStack {
public:
    /** initialize your data structure here. */
    vector<int> stack;
    vector<int> min;
    MinStack() {
        
    }
    
    void push(int x) {
        stack.push_back(x);
        if(min.size() && x > min.back()){
            min.push_back(min.back());
        }
        else if(!min.size() || x <= min.back())
            min.push_back(x);
    }
    
    void pop() {
        stack.pop_back();
        min.pop_back();
    }
    
    int top() {
        return stack.back();
    }
    
    int getMin() {
        return min.back();
    }
};

/**
 * 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();
 */
//Runtime: 16 ms, faster than 99.48%

class MinStack {
public:
    /** initialize your data structure here. */
    stack<pair<int,int>> st;
    
    MinStack() {
        
    }
    
    void push(int x) {
        int min;
        if(st.empty())
            min = x;
        else
            min = std::min(st.top().second,x);
        st.push({x,min});
    }
    
    void pop() {
        st.pop();
    }
    
    int top() {
        return st.top().first;
    }
    
    int getMin() {
        return st.top().second;
    }
};

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

以上是关于c_cpp 155. Min Stack的主要内容,如果未能解决你的问题,请参考以下文章

155. Min Stack

155. Min Stack

#Leetcode# 155. Min Stack

155. Min Stack - Unsolved

155. Min Stack

Leetcode 155. Min Stack