题目描述
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
我的解题
在存入x时,同时将此时栈的最小值存入
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(S.empty())
{
S.push(x);
S.push(x);
}
else
{
int val = S.top();
S.push(x);
if(val<x)
{
S.push(val);
}
else
{
S.push(x);
}
}
}
void pop() {
S.pop();
S.pop();
}
int top() {
int val=S.top();
S.pop();
int res = S.top();
S.push(val);
return res;
}
int getMin() {
return S.top();
}
private:
stack<int>S;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
执行用时 :24 ms, 在所有 C++ 提交中击败了94.14%的用户
内存消耗 :17.7 MB, 在所有 C++ 提交中击败了100.00%的用户