昨天因爲去學校耽誤,湖北人上學不容易呀
問題描述:
設計一個支持 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) —— 將元素 x 推入棧中。
pop() —— 刪除棧頂的元素。
top() —— 獲取棧頂元素。
getMin() —— 檢索棧中的最小元素。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/min-stack
示例:
輸入:
["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.
解題思路:
push(x) —— 將元素 x 推入棧中。
pop() —— 刪除棧頂的元素。
top() —— 獲取棧頂元素。
這三個方法調用棧的方法即可
但是getMin()方法實現,需要我們採用別的方法
這裏額外開闢一個棧,棧頂元素用來存儲棧內最小元素如圖
stack minstack
1 | 1 |
6 | 2 |
4 | 2 |
2 | 2 |
3 | 3 |
代碼如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
st1.push(x);
if(minst.empty()){
minst.push(x);
}else{
if(x<minst.top()){
minst.push(x);
}else{
minst.push(minst.top());
}
}
}
void pop() {
st1.pop();
minst.pop();
}
int top() {
return st1.top();
}
int getMin() {
return minst.top();
}
private:
stack<int> st1;
stack<int> minst;
};
/**
* 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();
*/