leetcode-155. 最小栈
题目
解法
辅助栈
用辅助栈存当前栈中的最小值
class MinStack {
private $stack = [];
private $minStack = [];
/**
* initialize your data structure here.
*/
function __construct() {
}
/**
* @param Integer $val
* @return NULL
*/
function push($val) {
array_push($this->stack, $val);
if (empty($this->minStack)) {
array_push($this->minStack, $val);
} elseif ($this->minStack[count($this->minStack) - 1] >= $val) {
array_push($this->minStack, $val);
}
}
/**
* @return NULL
*/
function pop() {
$val = array_pop($this->stack);
if ($this->minStack[count($this->minStack) - 1] == $val) {
array_pop($this->minStack);
}
return $val;
}
/**
* @return Integer
*/
function top() {
return $this->stack[count($this->stack) - 1];
}
/**
* @return Integer
*/
function getMin() {
return $this->minStack[count($this->minStack) - 1];
}
}
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/14842344.html