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.
int half(vector<int>& nums, int target, int begin, int end){
int p = (begin + end) / 2;
if(nums[begin] == target) return begin;
if(nums[p] == target) return p;
if(nums[end] == target) return end;
if(nums[begin] < nums[p]){
if(nums[begin] < target && target < nums[p]){
return half(nums, target, begin, p);
}
else{
return half(nums, target, p, end);
}
}
else if(nums[begin] == nums[p]){
return -1;
}
if(nums[p] < nums[end]){
if(nums[p] < target && target < nums[end]){
return half(nums, target, p, end);
}
else{
return half(nums, target, begin, p);
}
}
return -1;
}
int search(vector<int>& nums, int target){
if(nums.empty()){
return -1;
}
return half(nums, target, 0, nums.size() - 1);
}