minStack with JavaScript


  • 0
    N
    /**
     * initialize your data structure here.
     */
    var MinStack = function() {
        this._storage = {};
        this._index = 0;
    };
    
    /** 
     * @param {number} x
     * @return {void}
     */
    MinStack.prototype.push = function(x) {
        let min = this.getMin();
        
        if (min === undefined) {
            min = x;
        } else {
            min = Math.min(min, x);
        }
        this._storage[++this._index] = [x, min]; 
    };
    
    /**
     * @return {void}
     */
    MinStack.prototype.pop = function() {
        if(this._index) {
            let removed = this._storage[this._index][0];
            delete this._storage[this._index];
            this._index -= 1;
            return removed;
        }
    };
    
    /**
     * @return {number}
     */
    MinStack.prototype.top = function() {
        if(this._index) {
            return this._storage[this._index][0];
        }
    };
    
    /**
     * @return {number}
     */
    MinStack.prototype.getMin = function() {
        if(this._index) {
            return this._storage[this._index][1];
        }
    };
    
    /** 
     * Your MinStack object will be instantiated and called as such:
     * var obj = Object.create(MinStack).createNew()
     * obj.push(x)
     * obj.pop()
     * var param_3 = obj.top()
     * var param_4 = obj.getMin()
     */
    

Log in to reply
 

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