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)如果target==A[mid],那么直接返回mid;
(2)如果A[mid]<A[right],那么说明从mid到right是有序的(没有受到rotate的影响),那么只需要判断target是不是在mid到right之间,如果是则把左边缘移到m+1,否则就target在另一半,即把右边缘移到m-1。
(3)如果A[mid]>=A[right],那么说明从left到mid一定是有序的,同样只需要判断target是否在这个范围内,相应的移动边缘即可。
算法的时间复杂度是O(logn),空间复杂度是O(1)
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
if A is None or len(A) == 0: return -1
left, right = 0, len(A) - 1
while left <= right:
mid = left + (right - left) / 2
if A[mid] == target:
return mid
if A[left] <= A[mid]:
if A[left] <= target and A[mid] > target:
right = mid - 1
else:
left = mid + 1
else:
if target > A[mid] and target <= A[right]:
left = mid + 1
else:
right = mid - 1
return -1