-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathValidMountainArray.php
More file actions
45 lines (39 loc) · 1020 Bytes
/
ValidMountainArray.php
File metadata and controls
45 lines (39 loc) · 1020 Bytes
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 ValidMountainArray
{
public static function validMountainArray(array $arr): bool
{
if (empty($arr)) {
return false;
}
$n = count($arr);
[$i, $j] = [0, $n - 1];
while ($i + 1 < $n && $arr[$i] < $arr[$i + 1]) {
$i++;
}
while ($j > 0 && $arr[$j - 1] > $arr[$j]) {
$j--;
}
return $i > 0 && $i === $j && $j < $n - 1;
}
public static function validMountainArray2(array $arr): bool
{
if (empty($arr)) {
return false;
}
$n = count($arr);
[$start, $end] = [0, $n - 1];
while ($start < $end) {
if ($arr[$start] < $arr[$start + 1]) {
$start++;
} elseif ($arr[$end] < $arr[$end - 1]) {
$end--;
} else {
break;
}
}
return $start > 0 && $start === $end && $end < $n - 1;
}
}