Find Minimum in Rotated Sorted Array II, Search in Rotated Sorted Array II:
注意这两题都是对nums[mid]和nums[low]进行if...elif...else分支而不是nums[low]和nums[high],这几题就死记吧,靠reasoning总是记不牢。Find Minimum in Rotated Sorted Array II 容易记错的原因是有一个特殊分支检查nums[low]和nums[high]并可能提早返回。
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low = 0
high = len(nums)-1
while low<=high:
print low,high
if high-low<2:
return nums[low] if high-low==0 else min(nums[low],nums[high])
if nums[high]>nums[low]:
return nums[low]
mid = low + (high-low)/2
if nums[mid]>nums[low]:
low = mid+1
elif nums[mid]<nums[low]:
high = mid
else:
low+=1
return nums[low]