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 search(int A[], int n, int target) {
int hi,low;
low=0;
hi=n-1;
while(low<=hi){
int mid=(hi+low)/2;
if(A[mid]==target)
return mid;
else if(A[low]<=A[mid]){
if(A[low]<=target && target<A[mid])
hi=mid-1;
else
low=mid+1;
}
else{
if(A[mid]<target && target<=A[hi])
low=mid+1;
else
hi=mid-1;
}
}
return -1;
}
};
总结:
1. 关键思路:二分搜索
2. 先判断前半部分是不是递增的,当是递增时,把搜索区间变为前半部分,看target是否在区间内,如果不在怎把搜索区间设为后半部分。
3. 当前半部分不是递增的,判断target是否在后半区间内,若在在搜索区间设为该区间,否则在另外区间继续搜索。