1
- public boolean search (int [] nums , int target ) {
2
- int start = 0 , end = nums .length - 1 ;
3
-
4
- //check each num so we will check start == end
5
- //We always get a sorted part and a half part
6
- //we can check sorted part to decide where to go next
7
- while (start <= end ){
8
- int mid = start + (end - start )/2 ;
9
- if (nums [mid ] == target ) return true ;
10
-
11
- //if left part is sorted
12
- if (nums [start ] < nums [mid ]){
13
- if (target < nums [start ] || target > nums [mid ]){
14
- //target is in rotated part
15
- start = mid + 1 ;
1
+ class Solution {
2
+ public boolean search (int [] nums , int target ) {
3
+ int start = 0 ;
4
+ int end = nums .length - 1 ;
5
+ while (start <= end ){
6
+ int mid = (start + end ) / 2 ;
7
+ if (nums [mid ] == target )
8
+ return true ;
9
+ if (nums [mid ] > nums [start ]){
10
+ if (target < nums [mid ] && target >= nums [start ])
11
+ end = mid - 1 ;
12
+ else
13
+ start = mid + 1 ;
14
+ }else if (nums [mid ] < nums [start ]){
15
+ if (nums [mid ] < target && target <= nums [end ])
16
+ start = mid + 1 ;
17
+ else
18
+ end = mid - 1 ;
19
+
16
20
}else {
17
- end = mid - 1 ;
21
+ start ++ ;
18
22
}
19
- }else if (nums [start ] > nums [mid ]){
20
- //right part is rotated
21
-
22
- //target is in rotated part
23
- if (target < nums [mid ] || target > nums [end ]){
24
- end = mid -1 ;
25
- }else {
26
- start = mid + 1 ;
27
- }
28
- }else {
29
- //duplicates, we know nums[mid] != target, so nums[start] != target
30
- //based on current information, we can only move left pointer to skip one cell
31
- //thus in the worest case, we would have target: 2, and array like 11111111, then
32
- //the running time would be O(n)
33
- start ++;
34
23
}
24
+ return false ;
35
25
}
36
-
37
- return false ;
38
26
}
0 commit comments