Skip to content

Commit 50b945a

Browse files
committed
Time: 0 ms (100%), Space: 43.5 MB (93.51%) - LeetHub
1 parent 915bb6b commit 50b945a

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution {
2+
public int search(int[] nums, int target) {
3+
int pivot = findPivot(nums);
4+
if (pivot == -1) {
5+
// run normal binary search
6+
return binarySearch(nums, target, 0, nums.length - 1);
7+
}
8+
9+
// if pivot is found, two ascending sorted arrays found -> check if pivot is target. Otherwise, run binary search in each(separately)
10+
if (nums[pivot] == target) {
11+
return pivot;
12+
}
13+
if (target >= nums[0]) {
14+
return binarySearch(nums, target, 0, pivot - 1);
15+
} else {
16+
return binarySearch(nums, target, pivot + 1, nums.length - 1);
17+
}
18+
}
19+
20+
int binarySearch(int[] arr, int target, int start, int end) {
21+
while(start <= end) {
22+
// find the middle element
23+
// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
24+
int mid = start + (end - start) / 2;
25+
if (target < arr[mid]) {
26+
end = mid - 1;
27+
} else if (target > arr[mid]) {
28+
start = mid + 1;
29+
} else {
30+
// ans found
31+
return mid;
32+
}
33+
}
34+
return -1;
35+
}
36+
37+
int findPivot(int[] arr) {
38+
int start = 0;
39+
int end = arr.length - 1;
40+
while (start <= end) {
41+
int mid = start + (end - start) / 2;
42+
if (mid < end && arr[mid] > arr[mid + 1]) {
43+
return mid;
44+
}
45+
if (mid > start && arr[mid - 1] > arr[mid]) {
46+
return mid - 1;
47+
}
48+
if (arr[start] >= arr[mid]) {
49+
end = mid - 1;
50+
} else {
51+
start = mid + 1;
52+
}
53+
}
54+
return -1;
55+
}
56+
}

0 commit comments

Comments
 (0)