题目:
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.
解题思路:
(1)直接搜索 时间复杂度O(n) 其实这是最容易想到的解法
class Solution {
public:
int search(int A[], int n, int target) {
if(A == NULL || n <= 0)
return -1;
for(int i = 0; i < n; ++i)
if(A[i] == target)
return i;
return -1;
}
};
(2)二分搜索 属于从有序数组中查找某个值的变形 时间复杂度O(logn)
如果在l到r的区间内搜索,有如下两种情况:
1.A[l] < A[r] 那么表明区间是有序排列的,按照正常的二分搜索处理
2.A[l] > A[r] 这表明区间存在翻转,那么存在一个k,使得A[k]是区间内的最小值,这样,A[l]到A[k] 与A[k+1]到A[r]为两个有序数组
所以只需要对A[mid]与A[r]作比较:
1.如果A[mid] > A[r] 表明一定存在翻转,接下来只需要判断target的位置,如果target位于A[l]和A[mid]之间 ,r = mid – 1,否则l = mid + 1
2.r如果A[mid] < A[r] ,那么说明从m到r一定是有序的(没有受到rotate的影响),那么我们只需要判断target是不是在mid到r之间。如果target位于A[mid]和A[r]之间,正常二分搜索,把左边缘移到mid+1,l = mid + 1,否则,target在另一半,把右边缘移动到mid-1,r = mid – 1
class Solution {
public:
int search(int A[], int n, int target) {
if(NULL == A || 0 == n)
return -1;
int left = 0, right = n-1, mid = 0;
while(left <= right)
{
mid = left+(right-left)/2;
if(A[mid] == target)
return mid;
else if(A[mid] > A[right])//left
{
if(A[left] <= target && target < A[mid])
right = mid - 1;
else
left = mid + 1;
}
else//right
{
if(A[mid] < target && target <= A[right])
left = mid + 1;
else
right = mid - 1;
}
}
return -1;
}
};