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


2019-3-12 星期二   开始吧


827c7d1f89d66c6df8b185ebbcbbb5c2.png


题目描述

设计一个支持push,pop,top以及在恒定时间内检索最小元素的堆栈。


题目示例

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就是将元素压入栈顶(PHP中的array_unshift),pop就是弹出栈顶元素(PHP中的array_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 视频操作