leetcode-155. 最小栈

题目

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];
    }
}
posted @ 2021-06-02 18:10  吴丹阳-V  阅读(31)  评论(0编辑  收藏  举报