JS Solution one stack easy understand


  • 0
    G
    var MinStack = function() {
        this._stack = [];
    };
    
    /*
        Sequence: [3, 5, 1, 4, 2, 6]
        Stack:
            top [x = 6, min = 1]
                [x = 2, min = 1]
                [x = 4, min = 1]
                [x = 1, min = 1]
                [x = 5, min = 3]
            end [x = 3, min = 3]
    */
    MinStack.prototype.push = function(x) {
        if (0 === this._stack.length)
            // [x, min = x]
            this._stack.push([x, x])
        else {
            var min = this._stack[this._stack.length - 1][1];
            if (min > x) {
                this._stack.push([x, x]);
            } else {
                this._stack.push([x, min]);
            }
        }
    };
    
    
    MinStack.prototype.pop = function() {
        if (0 !== this._stack.length)
            this._stack.pop();
    };
    
    
    MinStack.prototype.top = function() {
        if (0 === this._stack.length)
            return null;
        else
            return this._stack[this._stack.length - 1][0];
    };
    
    
    MinStack.prototype.getMin = function() {
        if (0 === this._stack.length)
            return null;
        else
            return this._stack[this._stack.length - 1][1];    
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.