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.
Java:
public class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length ==0)
return -1;
return helper(nums, target, 0, nums.length-1);
}
public int helper(int[] array, int target, int left, int right)
{
if(left > right) return -1;
int mid = (right + left)/2;
if(array[mid] == target) return mid;
if(array[mid] < array[right])
{
if(target>array[mid] && target <= array[right])
return helper(array, target, mid+1, right);
else return helper(array, target, left, mid-1);
}
if(array[mid] >= array[left])
{
if(target < array[mid] && target >= array[left])
return helper(array, target, left, mid -1);
else return helper(array, target, mid+1, right);
}
return -1;
}
}