6. [code]包含min函數的棧
6.1. 題目
設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂的元素。
top() – 獲取棧頂元素。
getMin() – 檢索棧中的最小元素。
6.2. 思路
需要記錄棧的所有狀態下的最小值
棧的每個狀態,都需要有一個變量來記錄最小值
所以,需要用一個棧,存儲各個狀態的最小值
數據棧 最小值棧
6.3. 代碼
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
_data.push(x);
if(_min.empty()){
_min.push(x);
}
else{
if(x>_min.top()){
x = _min.top();
}
_min.push(x);
}
}
void pop() {
_data.pop();
_min.pop();
}
int top() {
return _data.top();
}
int getMin() {
return _min.top();
}
private:
std::stack<int> _data;
std::stack<int> _min;
};
/**
* 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();
*/