-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBinarySearch.php
49 lines (43 loc) · 1.11 KB
/
BinarySearch.php
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
46
47
48
49
<?php
declare(strict_types=1);
namespace leetcode;
class BinarySearch
{
public static function search(array &$nums, int $target): int
{
if (empty($nums)) {
return -1;
}
$n = count($nums);
[$left, $right] = [0, $n - 1];
while ($left <= $right) {
$mid = $left + intdiv($right - $left, 2);
if ($nums[$mid] > $target) {
$right = $mid - 1;
} elseif ($nums[$mid] < $target) {
$left = $mid + 1;
} else {
return $mid;
}
}
return -1;
}
public static function search2(array &$nums, int $target): int
{
if (empty($nums)) {
return -1;
}
[$left, $right] = [0, count($nums)];
while ($left < $right) {
$mid = $left + (($right - $left) >> 1);
if ($nums[$mid] > $target) {
$right = $mid;
} elseif ($nums[$mid] < $target) {
$left = $mid + 1;
} else {
return $mid;
}
}
return -1;
}
}