最小栈

题目描述

  1. 题目地址:https://leetcode.cn/problems/min-stack/
  2. 题目要求:
    设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
    实现 MinStack 类:
  • MinStack() 初始化堆栈对象。
  • void push(int val) 将元素val推入堆栈。
  • void pop() 删除堆栈顶部的元素。
  • int top() 获取堆栈顶部的元素。
  • int getMin() 获取堆栈中的最小元素。
  1. 题目示例
    image

解题思路

  1. 题目要求是在常数时间内,我们使用辅助栈的方法来解决该问题
  2. 分别定义一个数据栈辅助栈,数据栈支持push、pop、top操作,辅助栈的栈顶为当前的最小值
  3. 栈是仅在表尾进行插入删除操作,表尾为栈顶,表头为栈底
  4. void 0 ; //undefined

解题代码

var MinStack = function() {
    this.stack = [];
    this.minStk = [];       //初始化数据栈和辅助栈
};

MinStack.prototype.push = function(val) {
    this.stack.push(val);             //入栈操作
    if (this.minStk.length === 0 || val <= this.minStk[this.minStk.length - 1]) {
         this.minStk.push(val);      //minStk的栈顶为当前的最小值
   }
};

MinStack.prototype.pop = function() {
    const val = this.stack.pop();
    if (val !== void 0 && val === this.minStk[this.minStk.length - 1]) {
       this.minStk.pop();
   }

};

MinStack.prototype.top = function() {
    return this.stack[this.stack.length - 1];       //返回数据栈的栈顶元素

};

MinStack.prototype.getMin = function() {
    return this.minStk[this.minStk.length - 1];     //返回辅助栈的栈顶元素

};
posted @ 2022-08-18 09:31  fionna  阅读(13)  评论(0编辑  收藏  举报