MedianOfTwoSortedArrays   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 18
eloc 46
c 2
b 0
f 0
dl 0
loc 68
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B findMedianSortedArrays() 0 31 10
B findMedianSortedArrays2() 0 33 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MedianOfTwoSortedArrays
8
{
9
    public static function findMedianSortedArrays(array $num1, array $num2): float
10
    {
11
        if (empty($num1) && empty($num2)) {
12
            return 0;
13
        }
14
        $i = $j = $k = 0;
15
        [$m, $n] = [count($num1), count($num2)];
16
        $res = array_fill(0, $m + $n, 0);
17
        while ($i < $m && $j < $n) {
18
            if ($num1[$i] < $num2[$j]) {
19
                $res[$k++] = $num1[$i++];
20
            } elseif ($num1[$i] > $num2[$j]) {
21
                $res[$k++] = $num2[$j++];
22
            } else {
23
                $res[$k++] = $num1[$i++];
24
                $res[$k++] = $num2[$j++];
25
            }
26
        }
27
        while ($i < $m) {
28
            $res[$k++] = $num1[$i++];
29
        }
30
        while ($j < $n) {
31
            $res[$k++] = $num2[$j++];
32
        }
33
        if (($cnt = count($res)) % 2 === 0) {
34
            $mid = $cnt / 2;
35
36
            return (float) ($res[$mid] + $res[$mid - 1]) / 2;
37
        }
38
39
        return (float) $res[$k / 2];
40
    }
41
42
    public static function findMedianSortedArrays2(array $num1, array $num2): float
43
    {
44
        $i = $j = $k = 0;
45
        $v1 = $v2 = -1;
46
        [$m, $n] = [count($num1), count($num2)];
47
48
        for (; $k <= ($m + $n) / 2; $k++) {
49
            if ($i < $m && $j < $n) {
50
                if ($num1[$i] < $num2[$j]) {
51
                    $v2 = $v1;
52
                    $v1 = $num1[$i];
53
                    $i++;
54
                } else {
55
                    $v2 = $v1;
56
                    $v1 = $num2[$j];
57
                    $j++;
58
                }
59
            } elseif ($i === $m) {
60
                $v2 = $v1;
61
                $v1 = $num2[$j];
62
                $j++;
63
            } elseif ($j === $n) {
64
                $v2 = $v1;
65
                $v1 = $num1[$i];
66
                $i++;
67
            }
68
        }
69
70
        if (($m + $n) % 2 === 0) {
71
            return ($v1 + $v2) * 1.0 / 2;
72
        }
73
74
        return $v1;
75
    }
76
}
77