stackWithMin
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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; // 辅助栈
};