SortArrayByParity::sortArrayByParity2()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 16
rs 9.9332
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class SortArrayByParity
8
{
9
    public static function sortArrayByParity(array $arr): array
10
    {
11
        if (empty($arr)) {
12
            return [];
13
        }
14
        for ($i = 0, $j = 0, $n = count($arr); $j < $n; $j++) {
15
            if ($arr[$j] % 2 === 0) {
16
                $tmp = $arr[$i];
17
                $arr[$i++] = $arr[$j];
18
                $arr[$j] = $tmp;
19
            }
20
        }
21
22
        return $arr;
23
    }
24
25
    public static function sortArrayByParity2(array $arr): array
26
    {
27
        if (empty($arr)) {
28
            return [];
29
        }
30
        $n = count($arr);
31
        [$res, $start, $end] = [array_fill(0, $n, 0), 0, $n - 1];
32
        for ($i = 0; $i < $n; $i++) {
33
            if ($arr[$i] % 2 === 0) {
34
                $res[$start++] = $arr[$i];
35
            } else {
36
                $res[$end--] = $arr[$i];
37
            }
38
        }
39
40
        return $res;
41
    }
42
}
43