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.
这道题和一般的二分法查找有些不一样,在二分的时候,不能直接比较 A[mid]和target,而应该比较A[mid]和A[start]或A[end]的大小差别
class Solution {
public:
// 4 5 6 7 8 1 2 3
int search(int A[], int n, int target) {
int start = 0;
int end = n-1;
while (start <= end)
{
int mid = (start+end)/2;
/*
* the key point solution of this problem is we can not just compare the mid and target
* instead we should compare the mid and the start and end
* the following is wrong answer
*/
/*
if (A[mid] < A[end]) // left side
{
if (A[start] > target) // pivot is on the 45678123 find 1
{
start = mid+1;
}
else
{
end = mid-1;
}
}
else if (A[mid] < target) // right side
{
if (A[mid] < A[end]) // 45678123 find 8 || 513 find 5
{
start = mid+1;
}
else
{
start = mid+1;
}
}
else
{
return mid;
}
*/
if (A[mid] == target)
return mid;
if (A[mid] < A[end]) //be caureful, here we need to compare mid and end(start) not target
{
if (target > A[mid] && target <= A[end])
{
start = mid+1;
}
else
{
end = mid-1;
}
}
else
{
if (target >= A[start] && target < A[mid])
{
end = mid-1;
}
else
{
start = mid+1;
}
}
}
return -1;
}
};