MissingRanges::findMissingRanges()   B
last analyzed

Complexity

Conditions 8
Paths 16

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
c 2
b 0
f 0
dl 0
loc 20
rs 8.4444
cc 8
nc 16
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MissingRanges
8
{
9
    public static function findMissingRanges(array &$nums, int $lower, int $upper): array
10
    {
11
        $ans = [];
12
        if (empty($nums)) {
13
            return $ans;
14
        }
15
        foreach ($nums as $num) {
16
            if ($num > $lower) {
17
                $ans[] = $lower . ($num - 1 > $lower ? ('->' . ($num - 1)) : '');
18
            }
19
            if ($num === $upper) {
20
                return $ans;
21
            }
22
            $lower = $num + 1;
23
        }
24
        if ($lower <= $upper) {
25
            $ans[] = $lower . ($upper > $lower ? ('->' . $upper) : '');
26
        }
27
28
        return $ans;
29
    }
30
31
    public static function findMissingRanges2(array &$nums, int $lower, int $upper): array
32
    {
33
        $ans = [];
34
        if (empty($nums)) {
35
            return $ans;
36
        }
37
        $next = $lower;
38
        foreach ($nums as $num) {
39
            if ($lower === PHP_INT_MAX) {
40
                return $ans;
41
            }
42
            if ($num < $next) {
43
                continue;
44
            }
45
            if ($num === $next) {
46
                $next++;
47
                continue;
48
            }
49
            $ans[] = self::getRange($next, $num - 1);
50
            if ($num === PHP_INT_MAX) {
51
                return $ans;
52
            }
53
            $next = $num + 1;
54
        }
55
        if ($next <= $upper) {
56
            $ans[] = self::getRange($next, $upper);
57
        }
58
59
        return $ans;
60
    }
61
62
    private static function getRange(int $a, int $b): string
63
    {
64
        return $a === $b ? (string) $a : sprintf('%d->%d', $a, $b);
65
    }
66
}
67