PHP: 'rotate' an array?

后端 未结 14 1953
小鲜肉
小鲜肉 2020-11-28 14:16

is it possible to easily \'rotate\' an array in PHP ?

Like this: 1, 2, 3, 4 -> 2, 3 ,4 ,1

Is there some kind of built-in PHP function for this?

14条回答
  •  我在风中等你
    2020-11-28 15:01

    There's a task about array rotation on Hackerrank: https://www.hackerrank.com/challenges/array-left-rotation/problem.

    And proposed solution with array_push and array_shift will work for all test cases except the last one, which fails due to timeout. So, array_push and array_shift will give you not the fastest solution.

    Here's the faster approach:

    function leftRotation(array $array, $n) {
       for ($i = 0; $i < $n; $i++) {
           $value = array[$i]; unset(array[$i]); array[] = $value;
       }
       return array;
    }
    

提交回复
热议问题