-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0062. Search in Rotated Sorted Array.java
More file actions
37 lines (37 loc) · 1.05 KB
/
0062. Search in Rotated Sorted Array.java
File metadata and controls
37 lines (37 loc) · 1.05 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
public class Solution {
/**
* @param A: an integer rotated sorted array
* @param target: an integer to be searched
* @return: an integer
*/
public int search(int[] A, int target) {
if (A.length == 0) return -1;
int min = 0; //index of lowest number
for (int i = 1; i < A.length; i++) {
if (A[i] < A[i - 1]) {
min = i;
break;
}
}
if (A[min] == target) return min;
int low, high;
if (A[0] < target && min != 0) { //must be in first part or not at all
low = 0;
high = min - 1;
} else {
low = min;
high = A.length - 1;
} //now binary search acccording to set range
while (low <= high) {
int mid = (low + high) / 2;
if (A[mid] == target) {
return mid;
} else if (A[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}