-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path34.php
42 lines (39 loc) · 1.12 KB
/
34.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
<?php
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
public function searchRange($nums, $target)
{
return [$this->search($nums, $target, "first"), $this->search($nums, $target, "last")];
}
public function search($nums, $target, $search)
{
$left = 0;
$right = count($nums) - 1;
while ($left <= $right) {
$mid = floor(($right - $left) / 2) + $left;
if ($nums[$mid] == $target) {
if ($search == "first") {
if ($mid == 0 || $nums[$mid - 1] != $target) {
return $mid;
}
$right = $mid - 1;
} else {
if ($mid == count($nums) - 1 || $nums[$mid + 1] != $target) {
return $mid;
}
$left = $mid + 1;
}
} elseif ($nums[$mid] > $target) {
$right = $mid - 1;
} else {
$left = $mid + 1;
}
}
return -1;
}
}