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在无序一段,递归。代码如下:
class Solution {
public:
int search(int A[], int n, int target) {
int L=0, R=n-1, M;
while (L<=R) {
M = (L+R)/2;
if (target==A[M]) {
return M;
}
if (A[L]<=A[M]) { //[L,M]有序
if (A[L]<=target && target<A[M]) {
R = M - 1;
}
else {
L = M + 1;
}
}
else { //[M,R]有序
if (A[M]<target && target<=A[R]) {
L = M + 1;
}
else {
R = M - 1;
}
}
}
return -1;
}
};