您的位置:首页 > 其它

设计一个栈,出栈时弹出栈中最小的元素,时间复杂度为1

2012-09-02 22:31 253 查看
Given a few numbers, how will you push them into a stack such that whenever I pop the top most element from that stack, I get the
minimum number from the bunch. Also he wanted me to tell the pop push algorithm such that the order of insertion and popping should be O(1).

template <typename T>
class MinStack {
private:
std::stack<T> stack;
std::stack<T> min;
public:
MinStack() {}
void push(T elem) {
stack.push(elem);
min.push(std::min(elem, min.top());
}
std::pair<T, T> popValAndMin() {
T val = stack.top();
T minVal = min.top();
stack.pop();
min.pop();
return minVal;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐