Skip to content

Commit a81e5ff

Browse files
committed
Time: 0 ms (100%), Space: 45.1 MB (55.08%) - LeetHub
1 parent 7cb7ccc commit a81e5ff

File tree

1 file changed

+69
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)