題目詳情
設計一個支持 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。
- push(x) —— 將元素 x 推入棧中。
- pop() —— 刪除棧頂的元素。
- top() —— 獲取棧頂元素。
- getMin() —— 檢索棧中的最小元素。
示例:
輸入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
輸出:
[null,null,null,null,-3,null,0,-2]
解釋:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
——題目難度:簡單
運用輔助棧即可在常數時間內檢索到最小元素,下面代碼
class MinStack {
public:
stack<int> date; //數據棧
stack<int> min; //輔助棧
/** initialize your data structure here. */
void push(int x) {
date.push(x);
if( min.empty() || x<=min.top() ) {
min.push(x);
}
}
void pop() {
if( date.top() == min.top() ) {
min.pop();
}
date.pop();
}
int top() {
return date.top();
}
int getMin() {
return min.top();
}
};
結果