LCR 147.最小栈

​​题目来源:

        leetcode题目,网址:LCR 147. 最小栈 - 力扣(LeetCode)

解题思路:

        利用辅助栈获得一个栈中元素的非严格递减序列,最小值为递减栈中的值。

解题代码:

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

总结:

        没想出来,看题解区的。


你可能感兴趣的:(#,C++,LeetCode,C++)