-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-insert-position.php
65 lines (54 loc) · 1.4 KB
/
search-insert-position.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<body>
<?php
/*
Problem:
Lesson learned:
-
-
*/
$solution = new Solution();
$result;
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer
*
* Runtime 13 ms beats 56.67%, Memory 19.72mb beats 97.23%
*/
function searchInsert($nums, $target) {
$half = intdiv(count($nums),2);
$odd = count($nums)%2;
$result = 0;
switch($target <=> $nums[$half]){
case 0: //equal
return $half;
case -1: //$target less than current value
if(($half - 1) >= 0){
if($nums[$half-1] < $target){
return $half;
}
return $this->searchInsert(array_slice($nums, 0, $half), $target);
}else{
return 0;
}
break;
case 1: //$target larger than current value
if(($half + 1) < count($nums)){
if($nums[$half+1] > $target){
return $half+1;
}
return $half + $odd + $this->searchInsert(array_slice($nums, $half+$odd), $target);
}else{
return count($nums);
}
break;
}
return null;
}
}
?>
</body>
</html>