Test Failed
Push — master ( 5cce80...9c1f9d )
by Jinyun
02:11
created

BinarySearch::search()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 19
rs 9.5222
cc 5
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class BinarySearch
8
{
9
    public static function search(array &$nums, int $target): int
10
    {
11
        if (empty($nums)) {
12
            return -1;
13
        }
14
        $n = count($nums);
15
        [$left, $right] = [0, $n - 1];
16
        while ($left <= $right) {
17
            $mid = $left + intdiv($right - $left, 2);
18
            if ($nums[$mid] > $target) {
19
                $right = $mid - 1;
20
            } elseif ($nums[$mid] < $target) {
21
                $left = $mid + 1;
22
            } else {
23
                return $mid;
24
            }
25
        }
26
27
        return -1;
28
    }
29
30
    public static function search2(array &$nums, int $target): int
31
    {
32
        if (empty($nums)) {
33
            return -1;
34
        }
35
        [$left, $right] = [0, count($nums)];
36
        while ($left < $right) {
37
            $mid = $left + (($right - $left) >> 1);
38
            if ($nums[$mid] > $target) {
39
                $right = $mid;
40
            } elseif ($nums[$mid] < $target) {
41
                $left = $mid + 1;
42
            } else {
43
                return $mid;
44
            }
45
        }
46
47
        return -1;
48
    }
49
}
50