当前位置:网站首页>包含min函数的栈(js)
包含min函数的栈(js)
2022-07-30 05:56:00 【一枚小银子】
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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.思路分析:
要能得到栈内最小元素,容易想到用一个变量来存这个元素,但问题是这个元素出去以后,下一个最小元素呢?解决该问题就得专门用一个数组来存第一小第二小第三小...的元素们了,定义两个数组,主数组arr1用来做栈的出栈和入栈,副数组arr2用来存小元素。重点来了,
入栈时,若该元素小于等于当前最小元素,那该元素也要往arr2中放;
出栈时,若该元素是当前最小元素,arr2尾部的该元素也要一同出来;
由此,arr2中存的元素越往尾部越小,每次读尾部最后一个元素就是最小元素。
代码实现:
var MinStack = function() {
this.arr1 = []
this.arr2 = []
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.arr1.push(x)
if (!this.arr2.length || (this.arr2.length && x <= this.arr2[this.arr2.length - 1])) {
this.arr2.push(x)
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
const e = this.arr1.pop()
if (this.arr2[this.arr2.length - 1] === e) {
this.arr2.pop()
}
return e
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.arr1[this.arr1.length - 1]
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.arr2[this.arr2.length - 1]
};边栏推荐
猜你喜欢

什么是微服务?

Detailed explanation of numpy multidimensional array ndarray

Is it possible to use the same port for UDP and TCP?

“AI教练”请进家,家庭智能健身蓬勃发展

From catching up to surpassing, domestic software shows its talents

计算矩阵的逆源码(使用伴随矩阵,3×3的矩阵)

Go uses the mencached cache

RAID disk array

AI可通过X光片识别种族,但没人知道为什么

【雷达目标检测】恒定阈值法和恒虚警(CFAR)法及代码实现
随机推荐
架构设计指南 如何成为架构师
STL源码剖析:bound friend template friend代码测试和理解
sizeof
Rodrigues: vector representation of rotation matrices
Process and Scheduled Task Management
B站崩了,如果是你是那晚负责的开发人员你会怎么做?
阿里二面:Sentinel vs Hystrix 对比,如何选择?
Distance calculation from space vertex to straight line and its source code
window.open()的用法,js打开新窗体
MySQL什么时候用表锁,什么时候用行锁?
Universal js time date format conversion
DHCP principle and configuration
Electron日常学习笔记
头条二面:MySQL中有几种常见的 SQL 错误用法?
The terminal connection tools, rolling Xshell
限塑令下的新材料——聚乳酸(PLA)
The CTO said I was not advised to use SELECT *, why is that?
从 Google 离职,前Go 语言负责人跳槽小公司
向量的导数运算和向量叉乘以及点乘的导数运算
STL源码剖析:迭代器的概念理解,以及代码测试。