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

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
 

提示:

各函数的调用总次数不超过 20000 次

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

要求取最小值的复杂度是O(1),需要维护一个保存最小值的栈,栈保存到目前为止的最小值,所以随着元素入栈形成非严格递减序列,随着普通栈的出栈来判断存最小值栈的出栈。

代码:

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> s,ls;
    MinStack() {

    }
    
    void push(int x) {
        s.push(x);
        if(ls.empty() || ls.top() >= x) ls.push(x);
    }
    
    void pop() {
        if(!s.empty()) {
            if(s.top() == ls.top()) ls.pop();
            s.pop();
        };
    }
    
    int top() {
        return s.top();
    }
    
    int min() {
        return ls.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->min();
 */
如果觉得有帮助,点个推荐啦~
原文地址:https://www.cnblogs.com/8023spz/p/13716987.html