原题链接:Leecode 33. 搜索旋转排序数组
自己反正是用遍历做的,二分对我还是有点难度,学习学习
解法一:遍历
class Solution {
public:
int search(vector<int>& nums, int target) {
int n=nums.size();
if(target<nums[0])
{
if(target>nums[n-1])
return -1;
else
{
int i=n-1;
while(i>=0 && target<nums[i] )
i--;
i=max(0,i);
if(target==nums[i])
return i;
else
return -1;
}
}
else if(target>=nums[0])
{
int i=0;
while(i<n && target>nums[i] && nums[i]>=nums[0])
i++;
i=min(i,n-1);
if(target==nums[i])
return i;
else
return -1;
}
return -1;
}
};
方法二:官方二分
class Solution {
public:
int search(vector<int>& nums, int target) {
int l=0,r=nums.size()-1;
while(l<=r)
{
int mid=(l+r)>>1;
if(target==nums[mid])
return mid;
if(nums[l]<=nums[mid])
{
if(target>=nums[l] && target<nums[mid])
r=mid-1;
else
l=mid+1;
}
else
{
if(target>nums[mid] && target<=nums[r])
l=mid+1;
else
r=mid-1;
}
}
return -1;
}
};
后来自己写的二分:
class Solution {
public:
int binarysearch(vector<int>& nums, int target,int l,int r)
{
while(l<r)
{
int mid=l+(r-l)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]<target) l=mid+1;
else r=mid-1;
}
return r;
}
int search(vector<int>& nums, int target) {
int n=nums.size();
int l=0,r=0,res=0;
for(int i=0;i<n;i++)
{
if((i+1<n && nums[i]>nums[i+1]) || i==n-1)
{
r=i;
break;
}
}
if(target<nums[l])
{
l=r+1; r=n-1;
}
res=binarysearch(nums,target,l,r);
if(nums[res]==target) return res;
return -1;
}
};