搜索旋转排序数组
class Solution {
public:
int search(vector<int>& nums, int target) {
//旋转数组使用基本的二分查找算法
int low=0;
int high=nums.size()-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
{
if(nums[low]<nums[mid])//旋转数组在后面
{
if(nums[low]<target)//在递增区间
high=mid-1;
else if(nums[low]>target)//在旋转区间
low=mid+1;
else
return low;
}
else if(nums[low]>nums[mid])//旋转数组在前面
{
high=mid-1;
}
else
low=mid+1;
}
else if(nums[mid]<target)
{
if(nums[low]<nums[mid])//旋转数组在后
{
low=mid+1;
}
else if(nums[low]>nums[mid])//旋转数组在前
{
if(nums[low]>target)
low=mid+1;
else if(nums[low]<target)
high=mid-1;
else
return low;
}
else
low=mid+1;
}
}
return -1;
}
};