forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArray.java
More file actions
43 lines (35 loc) · 963 Bytes
/
Copy pathSearchInRotatedSortedArray.java
File metadata and controls
43 lines (35 loc) · 963 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
33
34
35
36
37
38
39
40
41
42
43
// Problem: http://oj.leetcode.com/problems/search-in-rotated-sorted-array/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/22864861
// 1988lilong@163.com
public class SearchInRotatedSortedArray {
public int search(int[] A, int target) {
int left = 0;
int right = A.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (A[mid] == target) {
return mid;
}
if (A[mid] >= A[left]) {
if (A[mid] > target && A[left] <= target) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (A[mid] < target && A[right] >= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] a = { 3, 1, 2 };
SearchInRotatedSortedArray slt = new SearchInRotatedSortedArray();
System.out.println(slt.search(a, 1));
System.out.println(slt.search(a, 4));
}
}