-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.php
More file actions
49 lines (30 loc) · 946 Bytes
/
binarySearch.php
File metadata and controls
49 lines (30 loc) · 946 Bytes
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
/**
* 给定一个n个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @param Integer[] $nums
* @param Integer $target
* @return Integer
*/
function search($nums, $target) {
$length = count($nums);
$low = 0;
$high = $length - 1;
while ($low <= $high){
$mid = intval(($low + $high) / 2);
if($nums[$mid] == $target){
return $mid;
}
if($nums[$mid] > $target){
$high = $mid - 1;
}else{
$low = $mid + 1;
}
}
return -1;
}
$nums = [-1,0,3,5,9,12];
$target = 10;
print_r(search($nums, $target));