-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMergeSortedArray.php
More file actions
45 lines (41 loc) · 1.06 KB
/
MergeSortedArray.php
File metadata and controls
45 lines (41 loc) · 1.06 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
<?php
declare(strict_types=1);
namespace leetcode;
class MergeSortedArray
{
public static function merge(array &$num1, int $m, array &$num2, int $n): void
{
[$i, $j, $k] = [$m - 1, $n - 1, $m + $n - 1];
while ($i >= 0 && $j >= 0) {
if ($num1[$i] > $num2[$j]) {
$num1[$k] = $num1[$i];
$i--;
$k--;
} else {
$num1[$k] = $num2[$j];
$j--;
$k--;
}
}
while ($i >= 0) {
$num1[$k] = $num1[$i];
$i--;
$k--;
}
while ($j >= 0) {
$num1[$k] = $num2[$j];
$j--;
$k--;
}
}
public static function merge2(array &$num1, int $m, array &$num2, int $n): void
{
[$i, $j, $k] = [$m - 1, $n - 1, $m + $n - 1];
while ($i >= 0 && $j >= 0) {
$num1[$k--] = $num1[$i] > $num2[$j] ? $num1[$i--] : $num2[$j--];
}
while ($j >= 0) {
$num1[$k--] = $num2[$j--];
}
}
}