forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSearchRotatedSortedArray.java
More file actions
32 lines (31 loc) · 924 Bytes
/
SearchRotatedSortedArray.java
File metadata and controls
32 lines (31 loc) · 924 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
public class Solution {
public int search(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = A.length;
int left = 0, right = len - 1;
while (left <= right){
int mid = left + ((right - left)/2);
if (A[mid] == target) return mid;
// Left half is sorted.
if (A[left] <= A[mid]){
if (A[left] <= target && target < A[mid]){
right = mid - 1;
}
else{
left = mid + 1;
}
}
// Right half is sorted.
else{
if (target <= A[right] && target > A[mid]){
left = mid + 1;
}
else{
right = mid - 1;
}
}
}
return -1;
}
}