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

吴亲库里 has written 98 articles

情绪只是对自己无能的愤怒

积分:4772 等级:P8 职业:php 城市:杭州

0 条回复

登录后才能进行评论,立即登录?