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.
Example
For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
Challenge
O(logN) time
观察上面的数据可以发现,旋转后4-7是有序的,0-2也是有序的,只是整体不再有序了。中间的转折点是0。
如果能找到转折点是最好的。但是没有这样的必要。
只需要在二分查找的过程中,判断target的搜索区域[left,right]区间是否包含转折点,如果不包含则像一般的二分查找一样进行,最终可以找到target的位置;如果[left,right]包含转折点,则继续二分。
class Solution {
/**
* param A : an integer ratated sorted array
* param target : an integer to be searched
* return : an integer
*/
public:
int search(vector<int> &A, int target) {
// write your code here
int len=A.size();
int min;
int left=0,right=len-1;
if(len==0){
return -1;
}
while(left<=right){
int mid=left+(right-left)/2;
if(A[mid]==target){
return mid;
}else if(A[mid]>A[right]){//此时转折点在mid右边
//target在左边有序区域
if(target>=A[left] && target<A[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{//此时转折点在mid左边
//target在右边有序区域
if(target>A[mid] && target<=A[right]){
left=mid+1;
}else{
right=mid-1;
}
}
}
//没找到返回-1
return -1;
}
};