当前位置:网站首页>剑指 Offer 30. 包含min函数的栈

剑指 Offer 30. 包含min函数的栈

2022-07-06 02:11:00 anieoo

原题链接:剑指 Offer 30. 包含min函数的栈

 

solution:
        用堆栈存储pair数据, first保存入栈元素,second保存最小值

class MinStack {
public:
    /** initialize your data structure here. */
    typedef pair<int,int> PII;
    stack<PII> stk;
    MinStack() {

    }
    
    //.first保存栈元素,.second保存最小值
    void push(int x) {
        if(stk.empty() || x < stk.top().second) {
            stk.push({x, x});
            return;
        }
        stk.push({x, stk.top().second});
    }
    
    void pop() {
        stk.pop();
    }
    
    int top() {
        return stk.top().first;
    }
    
    int min() {
        return stk.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->min();
 */
原网站

版权声明
本文为[anieoo]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42174306/article/details/125630596