当前位置:网站首页>包含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]
};
边栏推荐
- Oracle查看表空间使用率及爆满解决方案
- PXE efficient mass network capacity
- The CTO said I was not advised to use SELECT *, why is that?
- assert
- STL源码剖析:class template explicit specialization代码测试和理解
- Is it possible to use the same port for UDP and TCP?
- Equation Derivation Proof of Vector Triple Product
- 空间顶点到直线的距离计算及其源码
- sizeof
- Electron中设置菜单(Menu),主进程向渲染进程共享数据
猜你喜欢
随机推荐
go : go-redis set操作
New material under the plastic restriction order - polylactic acid (PLA)
The first artificial intelligence safety competition officially launched
go : go-redis list操作
Derivative Operations on Vectors and Derivative Operations on Vector Cross and Dot Products
Proof of distance calculation from space vertex to plane and its source code
Electron中设置菜单(Menu),主进程向渲染进程共享数据
What are the access modifiers, declaration modifiers, and keywords in C#?Literacy articles
debian problem
Rodrigues: vector representation of rotation matrices
UDP和TCP使用同一个端口,可行吗?
sizeof
MySQL master-slave replication configuration construction, one step in place
Process and Scheduled Task Management
From catching up to surpassing, domestic software shows its talents
LVM and disk quotas
Huawei released "ten inventions", including computing, intelligent driving and other new fields
空间直线到平面上的交点的计算证明及其源码
go : go-redis 基础操作
上传文件--文件类型大全,图片类型,文档类型,视频类型,压缩包类型