一、题目
二、代码
class Solution
{
//二分找分届 重新制定索引
//二分查找数字
public:
int search(vector<int>& nums, int target)
{
int i,j;
int return_int=0;
int left,right;
int middle;
int new_flag=1;
int over_index=0;
if(nums.size()<3)
{
for(i=0;i<nums.size();i++)
{
if(nums[i]==target) return i;
}
return -1;
}
left=0;
right=nums.size()-1;
std::cout<<" left "<<left<<std::endl;
std::cout<<" right "<<right<<std::endl;
//二分查找0
while(new_flag)
{
new_flag=0;
middle=(left+right)/2;
if(nums[middle]>nums[left])
{
left=middle;
new_flag=1;
}
if(nums[middle]<nums[right])
{
right=middle;
new_flag=1;
}
}
std::cout<<" left "<<left<<" "<<nums[left]<<std::endl;
std::cout<<" rgiht "<<right<<" "<<nums[right]<<std::endl;
for(i=left;i<=right;i++)
{
if(i<nums.size()-1)
{
if(nums[i+1]<nums[i])
{
over_index=i+1;
break;
}
}
}
std::cout<<"真正的初始下标 "<<over_index<<" 数值 "<<nums[over_index]<<std::endl;
std::cout<<"转换思路 基准不一定是0 基准由人而定 就让基准为over_index"<<std::endl;
left=over_index;
right=over_index-1+nums.size();
std::cout<<" left "<<left<<" "<<nums[left]<<std::endl;
std::cout<<" rgiht "<<right<<" "<<nums[right%nums.size()]<<std::endl;
if(nums[left]>target||nums[right%nums.size()]<target) return -1;
if(nums[left]==target) return left;
if(nums[right%nums.size()]==target) return right%nums.size();
std::cout<<"进入循环 "<<std::endl;
while(left<=right-2)
{
int middle=(left+right)/2;
std::cout<<"进入后 "<<std::endl;
std::cout<<"left "<<left<<std::endl;
std::cout<<"right "<<right<<std::endl;
std::cout<<"middle "<<middle<<std::endl;
std::cout<<"nums[mddle%nums.size()] "<<nums[middle%nums.size()]<<std::endl;
if(nums[middle%nums.size()]==target)
{
return middle%nums.size();
}
else if(nums[middle%nums.size()]<target)
{
left=middle;
}
else if(nums[middle%nums.size()]>target)
{
right=middle;
}
std::cout<<"left "<<left<<std::endl;
std::cout<<"right "<<right<<std::endl;
std::cout<<"middle "<<middle<<std::endl;
}
std::cout<<"跳出循环 "<<std::endl;
//可能在middle上 也可能在right上面 因为最终是不一定取到right的
std::cout<<"middle "<<middle%nums.size()<<" "<<nums[middle%nums.size()]<<std::endl;
std::cout<<"right "<<right%nums.size()<<" "<<nums[right%nums.size()]<<std::endl;
std::cout<<"成功到末尾 "<<std::endl;
if(nums[middle%nums.size()]==target) return middle%nums.size();
if(nums[right%nums.size()]==target) return right%nums.size();
return -1;
}
};