Search in Rotated Sorted Array
Suppose an array sorted in ascending order 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.
Solution
public class Solution {
public int search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int middle = start + (end - start) / 2;
if (nums[middle] == target ) {
return middle;
} else if (nums[middle] > nums[end]) {
if (target >= nums[start] && target < nums[middle]) {
end = middle;
} else {
start = middle;
}
} else {
if (target <= nums[end] && target > nums[middle] ) {
start = middle;
} else {
end = middle;
}
}
}
if (nums[start] == target) {
return start;
} else if (nums[end] == target) {
return end;
} else {
return -1;
}
}
}