1. 程式人生 > >LeetCode——最小棧

LeetCode——最小棧

 

方法一:使用了兩個棧(有些投機:P) 

class MinStack {
public:
    /** initialize your data structure here. */
    
    MinStack() {}
    
    void push(int x) {
        s1.push(x);
        if (s2.empty() || s1.top() <= s2.top())
            s2.push(x);
    }
    
    void pop() {
        if(!s2.empty() && s2.top() == s1.top())
            s2.pop();
        s1.pop();
    }
    
    int top() {
     return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
    private :
    stack<int> s1, 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();
 */

方法二:使用一個棧

class MinStack{
public:
    /** initialize your data structure here. */
    
    MinStack() 
    {min = INT_MAX;}            //注意初始化!!

    
    void push(int x) {
        if (x<= min)            //注意等號!!
        {
            s.push(min);
            min = x;
        }
        s.push(x);
    }
    
    void pop() {
       if(s.top() == min)
       {
           s.pop();
           min = s.top();
           s.pop();
       }
        else
        s.pop();
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
       return min;
    }
    private :
        long min;
        stack<int> s;
};

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