-
Notifications
You must be signed in to change notification settings - Fork 1
/
search-in-rotated-sorted-array-ii.php
53 lines (48 loc) · 1.32 KB
/
search-in-rotated-sorted-array-ii.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
<?php
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Boolean
*/
function search($nums, $target) {
$i = 0;
$j = count($nums) - 1;
while ($i <= $j) {
$middle = (int)(($i+$j)/2);
if ($nums[$middle] === $target) {
return true;
}
// 前部分有序
if ($nums[$i] < $nums[$middle]) {
if ($nums[$i] === $target) {
return true;
}
// 有序部分可以比较
if ($nums[$middle] > $target && $nums[$i] < $target) {
$j = $middle-1;
} else {
$i++;
}
} elseif ($nums[$i] === $nums[$middle]) {
$i++;
continue;
} else {
// 后部分有序
if ($nums[$j] === $target) {
return true;
}
if ($nums[$middle] < $target && $nums[$j] > $target) {
$i = $middle+1;
} else {
$j--;
}
}
}
return false;
}
}
$nums = [2,5,6,0,0,1,2];
$target = 3;
$ret = (new Solution())->search($nums, $target);
var_dump($ret);