题目
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 find_max(int a[],int n) //二分最大元素序号
{
if(a[0]<a[n-1])
return n-1;
int max=0;
int first=0,last=n-2,mid;
while(last>=first)
{
mid=(first+last)/2;
if(a[mid]>=a[max])
{
first=mid+1;
max=mid;
}
else
last=mid-1;
}
return max;
}
int search(int A[], int n, int target) {
int last=find_max(A,n);
int first=(last+1)%n;
if(target>A[last]||target<A[first])
return -1;
int mid;
bool flag=first; //last小于first的标志为,1表示小于
while((flag==true&&last<=first)||(flag==false&&first<=last)) //环形的二分查找
{
if(flag)
mid=((last+n+first)/2)%n;
else
mid=(first+last)/2;
if(A[mid]==target)
return mid;
else if(A[mid]>target)
{
last=mid-1;
if(last<0)
{
if(flag==false)
break;
else
last=n-1;
}
}
else
{
first=mid+1;
if(first>=n)
{
if(flag==false)
break;
else
first=0;
}
}
if(first<=last)
flag=false;
}
return -1;
}
};