Time: , space:
.
class Solution:
def search(self, nums: List[int], target: int) -> bool:
n = len(nums)
lo, hi = 0, n-1
while lo <= hi:
mid = (lo + hi)//2
if nums[mid] == target:
return True
# As long as nums[lo] != nums[hi]
# we can use same approach as if all
# numbers between lo and hi were distinct
if nums[lo] == nums[hi]:
lo += 1
continue
if nums[mid] >= nums[lo]: # mid is on the left of break
if target >= nums[lo] and target < nums[mid]:
hi = mid-1
else:
lo = mid+1
else:
if target > nums[mid] and target <= nums[hi]:
lo = mid+1
else:
hi = mid-1
return False
If all numbers were distinct, we could find which side of pivot is on by comparing
with
as below. Here, with duplicates allowed, we reduce the problem to the all-distinct case by making sure
.

Leave a comment