难度:Easy
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。 pop() -- 删除栈顶的元素。 top() -- 获取栈顶元素。 getMin() -- 检索栈中的最小元素。 示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
要设计一个支持返回最小值的栈,可以使用两个栈实现:一个支持push和pop、top等操作,另一个保存每次的最小值。
class MinStack {
private:
stack<int> num;
stack<int > m;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(num.empty()) m.push(x);
else m.push(min(m.top(),x));
num.push(x);
}
void pop() {
num.pop();
m.pop();
}
int top() {
return num.top();
}
int getMin() {
return m.top();
}
};
/**
* 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();
*/
执行用时 :36 ms, 在所有 C++ 提交中击败了97.28%的用户
内存消耗 :16.9MB, 在所有 C++ 提交中击败了69.68%的用户