zoukankan      html  css  js  c++  java
  • 面试题 03.02. 栈的最小值

    地址:https://leetcode-cn.com/problems/min-stack-lcci/

    <?php
    
    /**
     *
     * 请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
     *
     *
     * 示例:
     *
     * MinStack minStack = new MinStack();
     * minStack.push(-2);
     * minStack.push(0);
     * minStack.push(-3);
     * minStack.getMin();   --> 返回 -3.
     * minStack.pop();
     * minStack.top();      --> 返回 0.
     * minStack.getMin();   --> 返回 -2.
     */
    class MinStack {
        /**
         * initialize your data structure here.
         */
        private $stack = null;
        private $order = null;
    
        function __construct() {
            $this->stack = [];
            $this->order = [PHP_INT_MAX];
        }
    
        /**
         * @param Integer $x
         * @return NULL
         */
        function push($x) {
            $this->stack[] = $x;
            //截止目前最小值入栈
            if (end($this->order) > $x) {
                $this->order[] = $x;
            } else {
                $this->order[] = end($this->order);
            }
        }
    
        /**
         * @return NULL
         */
        function pop() {
            $x = array_pop($this->stack);
            array_pop($this->order);
            return $x;
        }
    
        /**
         * @return Integer
         */
        function top() {
            return end($this->stack);
        }
    
        /**
         * @return Integer
         */
        function getMin() {
    
            return end($this->order);
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * $obj = MinStack();
     * $obj->push($x);
     * $obj->pop();
     * $ret_3 = $obj->top();
     * $ret_4 = $obj->getMin();
     */
    
    $obj = new MinStack();
    $obj->push(-2);
    $obj->push(0);
    $obj->push(-3);
    $obj->pop();
    $res_3 = $obj->top();
    $ret_4 = $obj->getMin();
  • 相关阅读:
    C语言I博客作业05
    C语言I博客作业04
    C语言II博客作业04
    C语言II博客作业03
    C语言II—作业02
    C语言II博客作业01
    学期总结
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/13163873.html
Copyright © 2011-2022 走看看