题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
解决方案
class Solution {
public:
void push(int x) {
s1.push(x);
if(s2.empty() || x <= s2.top())
{
s2.push(x);
}
}
void pop() {
if(s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int min() {
return s2.top();
}
private:
stack<int> s1,s2;
};