小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
一、了解题目
附上原题链接: 155. 最小栈
难度: 简单 easy
题目如下:
设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
push(x)
—— 将元素 x
推入栈中。 pop()
—— 删除栈顶的元素。 top()
—— 获取栈顶元素。 getMin()
—— 检索栈中的最小元素。
二、题解分析
这道题会用到数据结构中的栈来解题。那么接下来我们来看下这道题的解题步骤,具体如下:
- 定义两个栈,
stack
栈放所有元素,temp
栈一个放最小元素; push
:所有元素都应该放进stack
栈,最小元素放进temp
栈;pop
:比较两个栈的栈顶元素,判断单方向弹出元素还是双方向弹出元素;top
:获取stack
栈中的栈顶元素;getMin
:获取temp
栈中的栈顶元素。
三、代码实现
依据上面的题解,我们将用 js
来实现这道题。具体实现代码如下:
/**
* @description leetcode 155.取出栈中最小元素
*/
let MinStack = function() {
// 定义两个栈,stack栈用来存放所有元素,temp栈用来存放最小元素
this.stack = [];
this.temp = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
// 1.stack栈用于存放所有元素,所以任何值都可以放进stack栈中
this.stack.push(x);
// 2.元素什么时候才能放进temp栈中?
// 2.1 第一种情况,当temp栈为空时,说明此时时第一个元素,还没有其他元素可以比较,那它必然时最小的,所以可以放进temp栈中;
// 2.2 第二种情况,当temp栈不为空时,那么说明栈里面已经有元素了;此时新加入的元素只能比原来栈中的栈顶元素小,才能放进去,否则旧没有放进去的意义。
if(this.temp.length==0||x<=this.temp[this.temp.length-1]){
this.temp.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
// 1.取出stack栈中的最后一个元素
const stackTop = this.stack[this.stack.length - 1];
// 2.取出temp栈中的最后一个元素
const tempTop = this.temp[this.temp.push - 1];
// 3.要在stack栈有元素的情况下才有可能进行pop操作
if(this.stack.length > 0){
// 3.1 判断stack栈的栈顶是否是最小元素;
// 如果是的话,则说明此时两个栈的栈顶是一样的;并把两个栈的栈顶同时弹出
if(stackTop === tempTop){
this.temp.pop();
this.stack.pop();
return null;
}
// 3.2 如果两个栈的栈顶元素不相等,则说明此时stack栈的栈顶不是最小元素,那么只要把stack的栈顶弹出即可
else{
this.stack.pop();
return null;
}
}else{
return null;
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
// 1. 先判断是否为空栈,空栈时返回null,不为空栈时返回栈的最后一个元素,栈的最后一个元素即栈顶
return this.stack.length > 0 ? this.stack[this.stack.length-1] : null;
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
// 1. 先判断stack是否为空栈,空栈时返回null,不为空栈时说明此时两个栈肯定都有元素;之后返回temp栈的最后一个元素,即最小值
return this.stack.length > 0 ? this.temp[this.temp.length-1] : null;
};
// 测试
let minstack = new MinStack();
minstack.push(-2);
minstack.push(0);
minstack.push(-3);
// minstack.push(-8);
// minstack.push(6);
minstack.getMin()
// console.log(minstack.getMin())
minstack.pop()
// console.log(minstack.pop())
minstack.top()
// console.log(minstack.top())
minstack.getMin()
console.log(minstack.getMin()) // -3
以上就是关于取出最小栈的题解,不知道对小伙伴们是否有帮助呢?
我们下期见👋👋👋