Leetcode之PHP版题目解析(189. Rotate Array)


2019-3-27   


 Leetcode之PHP版题目解析(172. Factorial Trailing Zeroes)


a8167322b464a3dd5e957e7c3cd21d97.png


Kk.


1[1,2,3,4,5,6,7],k3[5,6,7,1,2,3,4],kkk.

使php 

/**
     * @param Integer[] $nums
     * @param Integer $k
     * @return NULL
     */
    function rotate(&$nums, $k) {
        while($k>0){
              array_unshift($nums,array_pop($nums));
              $k--;
        } 
    }

/**
     * @param Integer[] $nums
     * @param Integer $k
     * @return NULL
     */
    function rotate(&$nums, $k) {
         $data=$nums;
         for($i=0;$i<count($nums);$i++) {
             $nums[($i+$k)% count($nums)]=$data[$i];
        }
    }

        

使O(1)2O(n),kk

a9c79638c62d82e33ffa2ec3d672bde5.png

/**
     * @param Integer[] $nums
     * @param Integer $k
     * @return NULL
     */
    function rotate(&$nums, $k) {
         $k %=count($nums);
         $this->reverse($nums,0,count($nums)-1);
         $this->reverse($nums,0,$k-1);
         $this->reverse($nums,$k,count($nums)-1);
    }
    
    function reverse(&$nums,$start,$end){
        while($start<$end){
            $res=$nums[$start];
            $nums[$start]=$nums[$end];
            $nums[$end]=$res;
            $start++;
            $end--;
        }
        
    }


Github整理地址:https://github.com/wuqinqiang/leetcode-php


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode PHP题解--D16 922. Sort Array By Parity II

>> 下一篇: Leetcode PHP题解--D17 883. Projection Area of 3D Shapes