-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFindPeakElement.php
More file actions
39 lines (33 loc) · 820 Bytes
/
FindPeakElement.php
File metadata and controls
39 lines (33 loc) · 820 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
<?php
declare(strict_types=1);
namespace leetcode;
class FindPeakElement
{
public static function findPeakElement(array $nums): int
{
if (empty($nums)) {
return 0;
}
$max = $nums[0];
foreach ($nums as $i => $num) {
$max = max($max, $num);
}
return array_flip($nums)[$max];
}
public static function findPeakElement2(array $nums): int
{
if (empty($nums)) {
return 0;
}
[$left, $right] = [0, count($nums) - 1];
while ($left < $right) {
$mid = $left + (int)(($right - $left) / 2);
if ($nums[$mid] < $nums[$mid + 1]) {
$left = $mid + 1;
} else {
$right = $mid;
}
}
return $left;
}
}