Created
July 24, 2021 11:14
-
-
Save riyafa/be3f6dfde69488a5ff999f14172d8723 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchInRotatedArray { | |
public int search(int[] nums, int target) { | |
return search(nums, 0, nums.length - 1, target); | |
} | |
private int search(int[] nums, int start, int end, int target) { | |
if (start > end) return -1; | |
int midIdx = start + (end - start) / 2; | |
int mid = nums[midIdx]; | |
if (target == mid) return midIdx; | |
int first = nums[start]; | |
int last = nums[end]; | |
if (first <= mid) { | |
if (target < mid && first <= target) { | |
return search(nums, start, midIdx - 1, target); | |
} else { | |
return search(nums, midIdx + 1, end, target); | |
} | |
} else { | |
if (target > mid && last >= target) { | |
return search(nums, midIdx + 1, end, target); | |
} else { | |
return search(nums, start, midIdx - 1, target); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment