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.
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
int low=0,high=nums.size()-1,middle;
while(low<=high){
middle=(low+high)/2;
if(target == nums[middle]){ //先确定middle值是不是target
return middle;
}
if(nums[low]<=nums[middle]){ //左边有序
if(nums[low]<=target && target<nums[middle]){ //target在middle左边区域
high=middle-1;
}else{
low=middle+1;
}
}else{ //右边有序
if(nums[middle]<target && target<=nums[high]){ //target在目标右边区域
low=middle+1;
}else{
high=middle-1;
}
}
}
return -1;
}
};