HZFE / algorithms-solving

1 stars 0 forks source link

2022-09-20 #53

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

155 Min Stack

/*
 * @lc app=leetcode id=155 lang=typescript
 *
 * [155] Min Stack
 */

// @lc code=start
class MinStack {
    stack = [] as number[]
    minStack = [] as number[]

    constructor() {

    }

    push(val: number): void {
        this.stack.push(val);

        const minVal = Math.min(val, this.minStack[this.minStack.length - 1] ?? val);

        // the top of minStack is always the minium value in the stack
        this.minStack.push(minVal);
    }

    pop(): void {
        this.stack.pop();
        this.minStack.pop();
    }

    top(): number {
        return this.stack[this.stack.length - 1];
    }

    getMin(): number {
        return this.minStack[this.minStack.length - 1];
    }
}

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

Nickname: Geeku From vscode-hzfe-algorithms