forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArray.java
More file actions
40 lines (35 loc) · 1.16 KB
/
SearchInRotatedSortedArray.java
File metadata and controls
40 lines (35 loc) · 1.16 KB
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
package Algorithms.array;
public class SearchInRotatedSortedArray {
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int left = 0;
int right = A.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (A[mid] == target) {
return mid;
}
// the left side is sorted.
if (A[mid] >= A[left]) {
if (target <= A[mid] && target >= A[left]) {
// target is in the left side.
right = mid - 1;
} else {
// target is in the right side.
left = mid + 1;
}
} else { // the right side is sorted.
if (target >= A[mid] && target <= A[right]) {
// target is in the right side.
left = mid + 1;
} else {
// target is in the right side.
right = mid - 1;
}
}
}
return -1;
}
}