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.
题目翻译:在不重复的循环有序数组(如0 1 2 3 4 5 6 7->4 5 6 7 0 1 2)中查找目标,返回下标,如果不存在则返回-1.
知识点:二分查找
难点:判断目标在左边[target,mid-1]还是[mid+1,end]-->用IsPossible(int start,int end,int target)判断。
AC代码:
class Solution {
public:
bool IsPossible(int start,int end,int target)
{
if(start==target||end==target)
return true;
if(start<end)
{
return(target>start&&target<end);
}else if(start>end)
{
return(target>start||target<end);
}else{
return false;
}
}
int search(int A[], int n, int target) {
int left=0,right=n-1;
while(left<=right)
{
int mid=(left+right)/2;
if(A[mid]==target)
return mid;
if(IsPossible(A[0],A[mid],target))
{
right=mid-1;/*target在mid左边*/
}
else
{
left=mid+1;/*target在mid右边*/
}
}
return -1;
}
};