Test Failed
Push — master ( 28c77f...a74a49 )
by Jinyun
02:29
created

FindPeakElement::findPeakElement2()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 16
rs 9.9332
cc 4
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class FindPeakElement
8
{
9
    public static function findPeakElement(array $nums): int
10
    {
11
        if (empty($nums)) {
12
            return 0;
13
        }
14
        $max = $nums[0];
15
        foreach ($nums as $i => $num) {
16
            $max = max($max, $num);
17
        }
18
19
        return array_flip($nums)[$max];
20
    }
21
22
    public static function findPeakElement2(array $nums): int
23
    {
24
        if (empty($nums)) {
25
            return 0;
26
        }
27
        [$left, $right] = [0, count($nums) - 1];
28
        while ($left < $right) {
29
            $mid = $left + (int)(($right - $left) / 2);
30
            if ($nums[$mid] < $nums[$mid + 1]) {
31
                $left = $mid + 1;
32
            } else {
33
                $right = $mid;
34
            }
35
        }
36
37
        return $left;
38
    }
39
}
40