[LeetCode]155. 最小栈 —— javascrip

设计一个支持 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;
	};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章