設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂的元素。
top() – 獲取棧頂元素。
getMin() – 檢索棧中的最小元素。
var MinStack = function() {
this.stack = []
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack[this.stack.length] = x;
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.length--;
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
var min = this.stack[0];
var len = this.stack.length;
for (var i=1; i<len; i++){
if (this.stack[i]<min){
min = this.stack[i];
}
}
return min;
};