旋转数组查找
程序员文章站
2022-03-06 08:22:47
...
题目:给定一个排序数组nums(nums中有无重复元素),且nums可能以某个未知下标旋转,给定目标值target,求target是否在nums中出现,若出现返回下标,未出现返回-1
算法思路
当target < nums[mid]:
if(nums[begin] < nums[mid])
(说明==递增区间== [begin,mid-1] ,==旋转区间==为[mid+1,end])
如果target >= nums[begin];
在递增区间[begin, mid-1]中查找
否则
在旋转区间[mid+1,end]中查找
if(nums[begin] > nums[mid])
(说明递增区间[mid+1,end],旋转区间[begin,mid-1])
直接在旋转区间[begin,mid-1]中查找
if(nums[begin] == nums[mid])
(说明目标只可能在[mid+1,end]间)
如target=1,数组[6,1]
int search(vector<int>& nums, int target){
int begin = 0;
int end = nums.size() - 1;
while(begin <= end)
{
int mid = (end - beigin) / 2;
if(target == nums[mid]);
return mid;
else if(target < nums[mid])
{
if(nums[begin] < nums[mid])
{
if(target >= nums[begin]
end = mid - 1;
else
begin = mid + 1;
}
else if(nums[begin] > nums[mid])
end = mid - 1;
else if(nums[begin] == nums[mid])
begin = mid + 1;
}
else if(target > nums[mid])
{
if(nums[begin] < nums[mid])
{
begin = mid + 1;
}
else if(nums[begin] > nums[mid])
{
if(target >= nums[begin]
end = mid - 1;
else
begin = mid + 1;
}
else if(nums[begin] == nums[mid])
begin = mid + 1;
}
}
return -1;
}