Suppose an array sorted in ascending order 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.
# 解题思路:
这题和普通的binary search有一点差别。和153的解题思路差不多。但是153更简单在只需要找到list中第一个小于最后一个数的数就好了。33这题需要再多讨论几种情况。
先分两种情况:
1. nums[start]<nums[mid]
再讨论, start<target<mid, end=mid #这里省略了nums[]
or t<s, start-mid
2. nums[start]>nums[mid]
再讨论, mid<target<end, start=mid
or target<mid, end=mid
代码示例:
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start,end=0,len(nums)-1
while(start<=end):
mid=start+(end-start)/2
if nums[mid]==target:
return mid
if nums[start]<=nums[mid]:
if nums[start]<=target and target<=nums[mid]:
end=mid-1
else:
start=mid+1
else: # start > mid
if target<=nums[end] and nums[mid]<=target: # target in [mid,end]
start=mid+1
else: # target<nums[mid]
end=mid-1
return -1
# 代码用了+1,-1这些倒是无所谓,稍微理解下和解题思路不冲突