时间限制:1秒 空间限制:32768K 题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
代码:
class Solution {
public:
void push(int value) {
st.push(value);
if(stackMin.empty())
stackMin.push(value);
else if(stackMin.top() < value)
stackMin.push(stackMin.top());
else
stackMin.push(value);
}
void pop() {
if(!st.empty()){
st.pop();
stackMin.pop();
}
}
int top() {
return st.top();
}
int min() {
return stackMin.top();
}
private:
stack<int> stackMin;
stack<int> st;
};