Skip to content

Instantly share code, notes, and snippets.

@riyafa
Created July 24, 2021 11:14
Show Gist options
  • Save riyafa/be3f6dfde69488a5ff999f14172d8723 to your computer and use it in GitHub Desktop.
Save riyafa/be3f6dfde69488a5ff999f14172d8723 to your computer and use it in GitHub Desktop.
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