qiaoxu123
12/31/2018 - 6:52 AM

155. Min Stack

  • 第一种解法:比较作弊,直接使用STL中的stack实现;

  • 第二种解法:使用vector数组实心,应该是比较理想的实现方法。

两种解法都需要一个额外的空间来实现最小元素的比较存放。

  • 第三种解法:比较特别,使用pair实现,通过这种方法减少了一个栈或者vector的使用,极大地提高了空间利用效率。时间复杂度也减少了好多。
//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();
 */