Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x)
– Push element x onto stack.pop()
– Removes the element on top of the stack.top()
– Get the top element.getMin()
– Retrieve the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
- Methods
pop
,top
andgetMin
operations will always be called on non-empty stacks.
題意:設計一個支持獲取最小值的棧,
思路:可以用數組或鏈表,從最底層搭建;這裏我使用的是STL的 stack
。
除了存儲數值的棧外,還定義一個存儲最小值的棧——如果新進入的值小於等於棧頂元素,則入棧,此時棧頂元素爲當前的最小值;getMin
總是取最小棧的棧頂元素;如果元素出棧,發現它是最小棧的棧頂元素,則最小棧也要出棧一次。
代碼:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> minVal, st;
MinStack() { }
void push(int x) {
if (minVal.empty()) minVal.push(x);
else if (x <= minVal.top()) minVal.push(x);
st.push(x);
}
void pop() {
if (!st.empty()) {
if (minVal.top() == st.top()) minVal.pop();
st.pop();
}
}
int top() { return st.top(); }
int getMin() { return minVal.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();
*/
效率:
執行用時:40 ms, 在所有 C++ 提交中擊敗了89.09% 的用戶
內存消耗:14.5 MB, 在所有 C++ 提交中擊敗了100.00% 的用戶