- how to handle repeated numbers (I did not think it through)
- figure out which part of the array to search
So I get the tricks from this solution: https://discuss.leetcode.com/topic/20593/python-easy-to-understand-solution-with-comments
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ start = 0 end = len(nums) - 1 while start <= end: mid = (start + end) / 2 if nums[mid] == target: return True while start < mid and nums[start] == nums[mid]: # tricky part, remove the repeatation start += 1 if nums[start] == target or nums[end] == target: return True if nums[start] <= nums[mid]: # rotation point is behind the mid point # first part is in order if nums[start] < target < nums[mid]: end = mid - 1 else: start = mid + 1 else: # rotation point is before the mid point # second part is in order if nums[mid] < target < nums[end]: start = mid + 1 else: end = mid -1 return False
No comments:
Post a Comment