LeetCode力扣 155. 最小棧 Min Stack 題解代碼 JavaScript

問題 https://leetcode-cn.com/problems/min-stack/

練習使用JavaScript解答

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.stack = [];
    this.order = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.stack.push(x);
    var i = this.order.length-1;
    if(i<0)
        this.order.push(x);
    else
        this.order.push((this.order[i] < x) ? this.order[i] : x );
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.stack.pop();
    this.order.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.stack[this.stack.length-1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.order[this.order.length-1];
};

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章