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

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

栈(Stack)的数据结构,本质上是一种Last-In-First-Out(LIFO)的线性数据结构。栈的核心操作包括push(压栈)、pop(弹栈)和top(获取栈顶元素)。为了实现栈中的最小值(min)查询,同时确保push、pop和min的时间复杂度均为O(1),我们需要引入一个辅助栈来维护当前栈中最小值的相关信息。

在本文中,我们将通过一个名为MinStack的数据类来实现上述目标。MinStack类包含两个栈:dataStack用来存储所有push进去的数据;minStack则用来存储辅助信息,辅助信息主要是帮助我们快速找到栈中的最小值。

核心思路

我们使用辅助栈(minStack)来维护当前栈中最小值的相关信息。具体来说:

  • push操作

    • 将数据push入dataStack。
    • 如果minStack为空,或者当前数据小于等于minStack的栈顶元素,则将数据也push入minStack。这样可以确保minStack始终保存当前栈中最小的元素。
  • pop操作

    • 如果当前栈的栈顶元素等于minStack的栈顶元素,则删除minStack的栈顶元素。这个操作的目的是为了确保当栈发生变化时,最小值的辅助信息能够及时更新。
  • min操作

    • 最直接的方式就是返回minStack的栈顶元素,因为minStack始终保存栈中最小的元素。
  • 这种方法可以在O(1)的时间复杂度内完成push、pop和min操作。

    代码实现

    以下是MinStack类的完整实现代码:

    var MinStack = function () {    this.dataStack = [];    this.minStack = [];};MinStack.prototype.push = function (x) {    this.dataStack.push(x);    const length = this.minStack.length;    if (length === 0 || x <= this.minStack[length - 1]) {        this.minStack.push(x);    }};MinStack.prototype.pop = function () {    const { minStack, dataStack } = this;    if (minStack[minStack.length - 1] === dataStack[dataStack.length - 1]) {        minStack.pop();    }    dataStack.pop();};MinStack.prototype.top = function () {    const length = this.dataStack.length;    if (!length) {        return null;    } else {        return this.dataStack[length - 1];    }};MinStack.prototype.min = function () {    const length = this.minStack.length;    if (!length) {        return null;    } else {        return this.minStack[length - 1];    }};

    总结

    通过引入辅助栈的方式,我们可以在O(1)的时间复杂度内实现栈的push、pop和min操作。这一设计巧妙地结合了栈的基本操作和最小值查询的需求,确保在处理大数据量时依然能够高效运行。这种设计方法既简洁又高效,是实现高性能栈操作的经典解决方案。

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

    你可能感兴趣的文章
    php20个主流框架
    查看>>
    php301到https,虚拟主机设置自动301跳转到HTTPS
    查看>>
    php5 apache 配置
    查看>>
    php5 升级 php7 版本遇到的问题处理方法总结
    查看>>
    PHP5.3.3安装Mcrypt扩展
    查看>>
    PHP5.4 + IIS + Win2008 R2 配置
    查看>>
    PHP5.4 pfsocketopen函数判断sock是否存活的bug(由memcached引起)
    查看>>
    Redis从入门到精通
    查看>>
    PHP5.6.x编译报错:Don't know how to define struct flock on this system, set --enable-opcache=no
    查看>>
    php5ts.dll 下载_php5ts.dll下载
    查看>>
    php7
    查看>>
    PHP7 新特性
    查看>>
    PHP7+MySQL5.7+Nginx1.9. on Ubuntu 14.0
    查看>>
    php7.1.6 + redis
    查看>>
    php7中使用php_memcache扩展
    查看>>
    PHP7中十个需要避免的坑
    查看>>
    php7和PHP5对比的新特性和性能优化
    查看>>
    PHP7安装pdo_mysql扩展
    查看>>
    PHP7实战开发简单CMS内容管理系统(7) 后台登录架构 用户登录校验
    查看>>
    php7,从phpExcel升级到PhpSpreadsheet
    查看>>