Search in Rotated Sorted Array
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.
Example
For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
Solution
S: 上道题最重要的是找到,Target的值,而这道题就是要确认中点的位置,在左上象限 或者是右下象限,然后根据Target的落入点进行排出,巧妙之处就是逐步排出,先把能排除的都排除掉,而左上mid 后面的可以慢慢的推出。
class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : an integer
"""
def search(self, num, target):
# write your code here
if len(num) == 0:
return -1
start, end = 0, len(num) - 1
while start + 1 < end:
mid = ( start + end ) / 2
if num[mid] == target:
return mid
if num[mid] > num[start]:
if target >= num[start] and target <= num[mid]:
end = mid
else:
start = mid
else:
if target >= num[mid] and target <= num[end]:
start = mid
else:
end = mid
if num[start] == target:
return start
if num[end] == target:
return end
return -1Last updated
Was this helpful?