Test Failed
Push — master ( ed702a...3fe7f5 )
by Jinyun
02:22
created

RotateArray::rotate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 11
rs 10
cc 4
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class RotateArray
8
{
9
    public static function rotate(array &$nums, int $k): void
10
    {
11
        if (empty($nums) || $k <= 0) {
12
            return;
13
        }
14
        [$ans, $n] = [[], count($nums)];
15
        foreach ($nums as $i => $num) {
16
            $ans[($i + $k) % $n] = $num;
17
        }
18
        ksort($ans);
19
        $nums = $ans;
20
    }
21
22
    public static function rotate2(array &$nums, int $k): void
23
    {
24
        if (empty($nums) || $k <= 0) {
25
            return;
26
        }
27
        $n = count($nums);
28
        $k = $k % $n;
29
        $nums = array_merge(
30
            array_slice($nums, $n - $k, $n),
31
            array_slice($nums, 0, $n - $k)
32
        );
33
    }
34
35
    public static function rotate3(array &$nums, int $k): void
36
    {
37
        if (empty($nums) || $k <= 0) {
38
            return;
39
        }
40
41
        $n = count($nums);
42
        $k = $k % $n;
43
        if ($k) {
44
            self::helper($nums, 0, $n - 1);
45
            self::helper($nums, 0, $k - 1);
46
            self::helper($nums, $k, $n - 1);
47
        }
48
    }
49
50
    private static function helper(array &$nums, int $i, int $j): void
51
    {
52
        while ($i < $j) {
53
            [$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]];
54
            $i++;
55
            $j--;
56
        }
57
    }
58
}
59