-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path33-Search-in-Rotated-Sorted-Array.java
More file actions
50 lines (44 loc) · 1.37 KB
/
33-Search-in-Rotated-Sorted-Array.java
File metadata and controls
50 lines (44 loc) · 1.37 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
class Solution {
public int search(int[] nums, int target) {
int pivot = findPivot(nums);
if(pivot == -1) {
return binarySearch(nums, target, 0, nums.length - 1);
} else if(nums[pivot] == target) {
return pivot;
} else if(nums[0] <= target) {
return binarySearch(nums, target, 0, pivot);
} else {
return binarySearch(nums, target, pivot+1, nums.length - 1);
}
}
public 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;
} else if(mid > start && nums[mid] < nums[mid-1]) {
return mid-1;
} else if(nums[start] < nums[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
public int binarySearch(int[] nums, int target, int start, int end) {
while(start <= end) {
int mid = start + (end - start)/2;
if(nums[mid] == target) {
return mid;
} else if(nums[mid] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}