博客
关于我
【剑指 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/

你可能感兴趣的文章
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>