-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Expand file tree
/
Copy pathSearchSortedRotatedArray.java
More file actions
54 lines (48 loc) · 1.59 KB
/
SearchSortedRotatedArray.java
File metadata and controls
54 lines (48 loc) · 1.59 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Given an array after the possible rotation and an integer target, return the index of target if it is in the array, or -1 if it is not in the array.
// eg Input: arr = [4,5,6,7,0,1,2], target = 0, Output: 4
class SearchRotatedSortedArray {
public int search(int[] arr, int target) {
int pivot = findPivot(arr);
if (pivot == -1) {
return binarySearch(arr, target, 0, arr.length - 1);
}
if (arr[pivot] == target) {
return pivot;
} else if (target >= arr[0]) {
return binarySearch(arr, target, 0, pivot - 1);
}
return binarySearch(arr, target, pivot + 1, arr.length - 1);
}
int binarySearch(int[] arr, int target, int start, int end) {
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
int findPivot(int[] nums) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid < end && nums[mid] > nums[mid + 1]) {
return mid;
}
if (mid > start && nums[mid] < nums[mid - 1]) {
return mid - 1;
}
if (nums[mid] < nums[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}