Passed
Push — master ( af3787...4c0964 )
by Jinyun
02:46
created

HeightChecker::heightChecker2()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 15
rs 9.9666
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class HeightChecker
8
{
9
    public static function heightChecker(array $heights): int
10
    {
11
        if (empty($heights)) {
12
            return 0;
13
        }
14
        $map = array_fill(0, 101, 0);
15
        foreach ($heights as $height) {
16
            $map[$height]++;
17
        }
18
        [$prev, $curr] = [0, 1];
19
        foreach ($heights as $height) {
20
            while ($map[$curr] === 0) {
21
                $curr++;
22
            }
23
            if ($curr !== $height) {
24
                $prev++;
25
            }
26
            $map[$curr]--;
27
        }
28
29
        return $prev;
30
    }
31
32
    public static function heightChecker2(array $heights): int
33
    {
34
        if (empty($heights)) {
35
            return 0;
36
        }
37
        $ordered = $heights;
38
        sort($ordered);
39
        [$cnt, $n] = [0, count($heights)];
40
        for ($i = 0; $i < $n; $i++) {
41
            if ($ordered[$i] !== $heights[$i]) {
42
                $cnt++;
43
            }
44
        }
45
46
        return $cnt;
47
    }
48
}
49