-
Notifications
You must be signed in to change notification settings - Fork 71
/
Question10SearchInRotatedSortedArray.java
47 lines (45 loc) · 1.48 KB
/
Question10SearchInRotatedSortedArray.java
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
package ninechapter.ch02_binary_search_and_sorted_array;
/**
* Created by anduo on 17-3-12.
* http://www.lintcode.com/zh-cn/problem/search-in-rotated-sorted-array/
* https://leetcode.com/problems/search-in-rotated-sorted-array
* 假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2);
* 给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
* 你可以假设数组中不存在重复的元素。
*/
public class Question10SearchInRotatedSortedArray {
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int start = 0;
int end = A.length;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
}
if (A[start] < A[mid]) {
if (A[start] <= target && target <= A[mid]) {
end = mid;
} else {
start = mid;
}
} else {
if (A[mid] <= target && target <= A[end]) {
start = mid;
} else {
end = mid;
}
}
}// end while
if (A[start] == target) {
return start;
}
if (A[end] == target) {
return end;
}
return -1;
}
}