Passed
Push — master ( 4366d3...c10d79 )
by Jinyun
55:26
created

FixedPoint::fixedPoint()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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