博客
关于我
【剑指 Offer 30】js 包含min函数的栈
阅读量:664 次
发布时间:2019-03-15

本文共 1618 字,大约阅读时间需要 5 分钟。

包含min函数的栈

题目

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.min();   --> 返回 -3.minStack.pop();minStack.top();      --> 返回 0.minStack.min();   --> 返回 -2.

提示:

  1. 各函数的调用总次数不超过 20000 次

思路

借助一个辅助栈,其中:辅助栈的栈顶元素,就是原栈中最小值。

原栈和辅助栈的处理过程:

  • 元素压入原栈时,如果辅助栈为空或元素<=辅助栈的栈顶元素,元素也压入辅助栈
  • 元素弹出原栈时,如果元素 = 辅助栈栈顶元素,辅助栈也弹出元素

注意:这里的判断条件是元素<=辅助栈栈顶元素 而不是元素 < 辅助栈栈顶元素,这是为了应对重复元素

/** * initialize your data structure here. */var MinStack = function () {     this.dataStack = [];  this.minStack = [];};/**  * @param {number} x * @return {void} */MinStack.prototype.push = function (x) {     this.dataStack.push(x);  const length = this.minStack.length;  if (!length || x <= this.minStack[length - 1]) {       this.minStack.push(x);  }};/** * @return {void} */MinStack.prototype.pop = function () {     const {    minStack, dataStack } = this;  if (minStack[minStack.length - 1] === dataStack[dataStack.length - 1]) {       minStack.pop();  }  dataStack.pop();};/** * @return {number} */MinStack.prototype.top = function () {     const length = this.dataStack.length;  if (!length) {       return null;  } else {       return this.dataStack[length - 1];  }};/** * @return {number} */MinStack.prototype.min = function () {     const length = this.minStack.length;  if (!length) {       return null;  } else {       return this.minStack[length - 1];  }};/** * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(x) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.min() */

image-20210209141240664

转载地址:http://yqqmz.baihongyu.com/

你可能感兴趣的文章
NIO笔记---上
查看>>
NIO蔚来 面试——IP地址你了解多少?
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NISP国家信息安全水平考试,收藏这一篇就够了
查看>>
NIS服务器的配置过程
查看>>
NIS认证管理域中的用户
查看>>
Nitrux 3.8 发布!性能全面提升,带来非凡体验
查看>>
NiuShop开源商城系统 SQL注入漏洞复现
查看>>
NI笔试——大数加法
查看>>
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 模型中的偏差和公平性检测
查看>>
Vue3.0 性能提升主要是通过哪几方面体现的?
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP、CV 很难入门?IBM 数据科学家带你梳理
查看>>
NLP三大特征抽取器:CNN、RNN与Transformer全面解析
查看>>
NLP入门(六)pyltp的介绍与使用
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>