Leetcode之PHP版题目解析(155. Min Stack)


2019-3-12 期二   


827c7d1f89d66c6df8b185ebbcbbb5c2.png


pushpoptop以及


MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

push(PHParray_unshift),pop(PHParray_shift),getMin().


()

     /**
     * initialize your data structure here.
     */
    private $data=[];
    
    function __construct() {
       
    }
  
    /**
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
         array_unshift($this->data,$x);
        
    }
  
    /**
     * @return NULL
     */
    function pop() {
          array_shift($this->data);
    }
  
    /**
     * @return Integer
     */
    function top() {
            return $this->data[0];
    }
  
    /**
     * @return Integer
     */
    function getMin() {
       return min($this->data);
    }


434c4422d5d5f42b51a8f4fd6440930e.png


.


    /**
     * initialize your data structure here.
     */
    private $data=[];
    private $min=[];
    
    function __construct() {
       
    }
  
    /**
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
         array_unshift($this->data,$x);
        if(count($this->min)==0 || $x<=$this->getMin()) {
            array_unshift($this->min,$x);
        }
    }
  
    /**
     * @return NULL
     */
    function pop() {
          $value=array_shift($this->data);
        if(count($this->min)>0 && $value===$this->getMin()){
            array_shift($this->min);
        }
        
    }
  
    /**
     * @return Integer
     */
    function top() {
        return $this->data[0];
    }
  
    /**
     * @return Integer
     */
    function getMin() {
        return min($this->min);
    }

0070790a4a94da45972cc9341cc23d56.png


min(),题目的要求是在恒定的时间内检索出最小元素,更优解留给你们思考吧


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Homestead 在windows 开启 nfs 后,npm install 报错

>> 下一篇: FFmpeg 视频操作