Skip to content

Commit 68fe248

Browse files
committed
Solution of Search in rotated sorted array 2 in java with explanation
1 parent 0d745b7 commit 68fe248

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public boolean search(int[] nums, int target) {
2+
int start = 0, end = nums.length - 1, mid = -1;
3+
while(start <= end) {
4+
mid = (start + end) / 2;
5+
if (nums[mid] == target) {
6+
return true;
7+
}
8+
//If we know for sure right side is sorted or left side is unsorted
9+
if (nums[mid] < nums[end] || nums[mid] < nums[start]) {
10+
if (target > nums[mid] && target <= nums[end]) {
11+
start = mid + 1;
12+
} else {
13+
end = mid - 1;
14+
}
15+
//If we know for sure left side is sorted or right side is unsorted
16+
} else if (nums[mid] > nums[start] || nums[mid] > nums[end]) {
17+
if (target < nums[mid] && target >= nums[start]) {
18+
end = mid - 1;
19+
} else {
20+
start = mid + 1;
21+
}
22+
//If we get here, that means nums[start] == nums[mid] == nums[end], then shifting out
23+
//any of the two sides won't change the result but can help remove duplicate from
24+
//consideration, here we just use end-- but left++ works too
25+
} else {
26+
end--;
27+
}
28+
}
29+
30+
return false;
31+
}

0 commit comments

Comments
 (0)