leetcode 155 最小栈

https://leetcode-cn.com/problems/min-stack/

leetcode 155 最小栈_第1张图片
水题,因为要在常数时间获取最小值,再开一个栈来存放相对应的最小值即可
代码

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

你可能感兴趣的:(随笔,code)