stackWithMIn

来源:互联网 发布:php中字符串的截取 编辑:程序博客网 时间:2024/06/05 11:16

stackWithMin

牛客网url

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
时间复杂度为O(1),使用一个辅助栈来实现,额外使用O(n)空间。

class Solution {public:    void push(int value) {        stack1.push(value);        if (stackMin.empty()){            stackMin.push(value);        } else {           if (value <= stackMin.top()){               stackMin.push(value);           }        }    }    void pop() {        int num = stack1.top();        stack1.pop();        if (num == stackMin.top()){            stackMin.pop();        }    }    int top() {        return stack1.top();    }    int min() {        return stackMin.top();    }private:    stack<int > stack1;         stack<int > stackMin;   // 辅助栈};
原创粉丝点击