-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSortArrayByParityII.php
More file actions
54 lines (48 loc) · 1.21 KB
/
SortArrayByParityII.php
File metadata and controls
54 lines (48 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace leetcode;
class SortArrayByParityII
{
public static function sortArrayByParityII(array $nums): array
{
if (empty($nums)) {
return [];
}
$n = count($nums);
[$i, $j] = [0, 1];
while ($i < $n && $j < $n) {
while ($i < $n && $nums[$i] % 2 === 0) {
$i += 2;
}
while ($j < $n && $nums[$j] % 2 === 1) {
$j += 2;
}
if ($i < $n && $j < $n) {
$tmp = $nums[$i];
$nums[$i] = $nums[$j];
$nums[$j] = $tmp;
}
}
return $nums;
}
public static function sortArrayByParityII2(array $nums): array
{
if (empty($nums)) {
return [];
}
$n = count($nums);
[$i, $j] = [0, 1];
while ($i < $n && $j < $n) {
if ($nums[$i] % 2 === 0) {
$i += 2;
} elseif ($nums[$j] % 2 === 1) {
$j += 2;
} else {
[$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]];
$i += 2;
$j += 2;
}
}
return $nums;
}
}