星星博客 »  > 

46 - 算法 - Leetcode-155-最小栈

//更新当前的状态 不要漏掉了

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> temStack;
    int min=INT_MAX;  //当前最小值
    MinStack() {
		
    }
    
    void push(int val) {
        if(val <= min) min = val;
        temStack.push(min);
        temStack.push(val);      
    }
    
    void pop() {
        temStack.pop();
        temStack.pop();
        if(!temStack.empty())
        {
            min = getMin();
        }
        else
        {
            min = INT_MAX;
        }
    }
    
    int top() {
        return temStack.top();
    }
    
    int getMin() {
        int temp = temStack.top();
        temStack.pop();
        int res = temStack.top();
        temStack.push(temp);
        return res;
    }
};

相关文章