Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Example:
For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
Challenge:
O(logN) time
Solution:
Since the time complexity is O(logN), we have to use binary search to reduce the SEARCH SPACE. Assume we have a sorted array [c, ..., b] and we rotate it at pivot a, then we have a rotated array [a, ..., b, c, ...., d], where c is the smallest value and b is the largest. A similar idea to Find Minimum in Rotated Sorted Array.
In this scenario, we could reduce the search space by following two cases:
- a <= target <= nums[mid], where a <= nums[mid],
- nums[mid] <= target <= d, where a > nums[mid].
Code:
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[start] <= nums[mid]) {
if (nums[start] <= target && target <= nums[mid]) {
end = mid;
} else {
start = mid;
}
} else {
if (nums[mid] <= target && target <= nums[end]) {
start = mid;
} else {
end = mid;
}
}
}
if (nums[start] == target) {
return start;
}
if (nums[end] == target) {
return end;
}
return -1;
}