題目說明
設計一個支持 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.
提示:
pop、top 和 getMin 操作總是在 非空棧 上調用。
解題思路一
- 首先確定棧的特點吧,
先進後出
,只能從棧頂進棧出棧
,然後我們用數組來模擬他,將數組末尾
當作棧頂
,在此進棧出棧。
- 其實就是實現一個數組的
push,pop
功能,然後增加獲取最小值
的api和返回數組最後一位
的api
- 由於最開始棧爲空,所以棧是通過
push
,或者pop
得到的。並且題目要求最小值要通過常數次操作得到,也就getMin
的時間複雜度爲O(1)
.那我們可以在push,pop的過程中,確定最小值。
代碼實現一
var MinStack = function() {
return void (
this.stack = [],
this.min = [Number.MAX_SAFE_INTEGER],
this.topValue = null
);
};
MinStack.prototype.push = function(x) {
return void (this.stack[this.stack.length] = x, this.topValue = x, this.min[this.min.length] = (x > this.min[this.min.length - 1] ? this.min[this.min.length - 1] : x));
};
MinStack.prototype.pop = function() {
return void (this.stack.length -= 1, this.topValue = this.stack[this.stack.length - 1], this.min.length -= 1);
};
MinStack.prototype.top = function() {
return this.topValue;
};
MinStack.prototype.getMin = function() {
return this.min[this.min.length - 1];
};