Intuition
In a rotated sorted array, at least one side of any midpoint is fully
sorted. Identify that side; check whether target lies in its range; if yes
search there, otherwise search the other half.
Explanation
Approach
For each step, compare nums[l] with nums[mid]:
- If
nums[l] <= nums[mid], the left half[l..mid]is sorted.- If
nums[l] <= target < nums[mid], search left (r = mid - 1). - Else search right (
l = mid + 1).
- If
- Else the right half
[mid..r]is sorted.- If
nums[mid] < target <= nums[r], search right. - Else search left.
- If
Implementation
import java.util.*;
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) return mid;
if (nums[l] <= nums[mid]) {
if (nums[l] <= target && target < nums[mid]) r = mid - 1;
else l = mid + 1;
} else {
if (nums[mid] < target && target <= nums[r]) l = mid + 1;
else r = mid - 1;
}
}
return -1;
}
}