-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHeightChecker.php
48 lines (42 loc) · 1009 Bytes
/
HeightChecker.php
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
<?php
declare(strict_types=1);
namespace leetcode;
class HeightChecker
{
public static function heightChecker(array $heights): int
{
if (empty($heights)) {
return 0;
}
$map = array_fill(0, 101, 0);
foreach ($heights as $height) {
$map[$height]++;
}
[$cnt, $curr] = [0, 1];
foreach ($heights as $height) {
while ($map[$curr] === 0) {
$curr++;
}
if ($curr !== $height) {
$cnt++;
}
$map[$curr]--;
}
return $cnt;
}
public static function heightChecker2(array $heights): int
{
if (empty($heights)) {
return 0;
}
$ordered = $heights;
sort($ordered);
[$cnt, $n] = [0, count($heights)];
for ($i = 0; $i < $n; $i++) {
if ($ordered[$i] !== $heights[$i]) {
$cnt++;
}
}
return $cnt;
}
}