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.
就是在一个移位以后的有序数组中找target。
二分的变种
确定有序的一边
如果target的范围处于有序的那边,则在有序的那边查找
如果target的范围不在有序的那边,则在另一半边查找。
class Solution {
public:
int search(int A[], int n, int target) {
int start = 0;
int end = n-1;
while(start<=end){
int mid = (start+end)/2;
if(A[mid]==target)
return mid;
if(A[mid]>=A[start]){//left to mid is sorted
if(A[start]<=target && A[mid]>=target)
end = mid-1;
else{
start = mid+1;
}
}else{
if(A[mid]<=target && A[end]>=target)
start = mid+1;
else
end = mid-1;
}
}
return -1;
}
};