js.最小栈

发布于:2025-09-15 ⋅ 阅读:(23) ⋅ 点赞:(0)

链接:https://leetcode.cn/problems/min-stack/description/?envType=study-plan-v2&envId=top-interview-150

题目:

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

实现 MinStack 类:

  • MinStack() 初始化堆栈对象。
  • void push(int val) 将元素val推入堆栈。
  • void pop() 删除堆栈顶部的元素。
  • int top() 获取堆栈顶部的元素。
  • int getMin() 获取堆栈中的最小元素。

代码:


var MinStack = function() {
    MinStack.prototype.arr = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {
    MinStack.prototype.arr.push(val);
};

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

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

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    let min = MinStack.prototype.arr[0], arr = MinStack.prototype.arr;
    for(let i = 1; i < arr.length ; i++) {
        if(arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
};

/** 
 * 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()
 */

题解代码:

var MinStack = function() {
    this.x_stack = [];
    this.min_stack = [Infinity];
};

MinStack.prototype.push = function(x) {
    this.x_stack.push(x);
    this.min_stack.push(Math.min(this.min_stack[this.min_stack.length - 1], x));
};

MinStack.prototype.pop = function() {
    this.x_stack.pop();
    this.min_stack.pop();
};

MinStack.prototype.top = function() {
    return this.x_stack[this.x_stack.length - 1];
};

MinStack.prototype.getMin = function() {
    return this.min_stack[this.min_stack.length - 1];
};