题目描述
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 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 search(int A[], int n, int target) {
int first=0;
int last=n-1;
while(first<=last)
{
int mid=first+(last-first)/2;
if(A[mid]==target)
return mid;
if(A[first]<=A[mid])//左边有序
{
if(A[first]<=target&&target<A[mid])
last=mid-1;
else
first=mid+1;
}
else//右边有序
{
if(A[mid]<target&&target<=A[last])
first=mid+1;
else
last=mid-1;
}
}
return -1;
}
};