来自力扣leetcode题库里面的第155题,《最小栈》
链接:https://leetcode-cn.com/problems/min-stack
题目为:
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
先说一下思路
我用的是数据栈+辅助栈的形式做的,数据栈用来存储所有的数据,辅助栈存储push命令时的那一刻的最小值,因为栈只有一个口是可以进行写入和弹出的,所以,在写入的那一时刻,最小值是不会变的,在pop的时候,判断一下这个pop的值是不是当前的最小值,如果是,也把存储最小值的辅助栈pop一下,这样操作完事之后,最小值还是辅助栈的最外面那个值。有点罗嗦,看代码
class MinStack
{
private $array;
private $minArray;
private $top;
private $min;
/**
* initialize your data structure here.
* TODO: 我是使用数组函数进行实现的,因为我觉得用php里面原声的栈函数很low哈哈哈(new SplStack())
*/
function __construct() {
$this->array = [];
$this->minArray = [];
$this->top = null;
$this->min = null;
}
function push(int $x) {
if (($this->min !== null && $this->min >= $x) || $this->min === null) {
$this->min = $x;
array_push($this->minArray, $x);
}
$this->top = $x;
array_push($this->array, $x);
return null;
}
function pop() {
if (!$this->array) return null;
$now = array_pop($this->array);
if ($now == $this->min) {
array_pop($this->minArray);
if ($this->minArray) {
$this->min = array_pop($this->minArray);
array_push($this->minArray, $this->min);
} else {
$this->min = null;
}
}
if ($this->array) {
$this->top = array_pop($this->array);
array_push($this->array, $this->top);
}
return $now;
}
function top() {
return $this->top;
}
function getMin() {
return $this->min;
}
}